1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-07-24 17:35:35 +02:00

initial population

This commit is contained in:
David Dykstal 2007-03-22 14:52:36 +00:00
parent 485678d02c
commit 2f0f316cfb
191 changed files with 31083 additions and 0 deletions

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1 @@
bin

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.eclipse.rse.importexport</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,11 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Importexport Plug-in
Bundle-SymbolicName: org.eclipse.rse.importexport; singleton:=true
Bundle-Version: 1.0.0
Bundle-ClassPath: systemsImportExport.jar
Bundle-Activator: org.eclipse.rse.importexport.RemoteImportExportPlugin
Bundle-Localization: plugin
Export-Package: org.eclipse.rse.files.importexport,org.eclipse.rse.files.importexport.files,org.eclipse.rse.importexport
Require-Bundle: org.eclipse.core.runtime,org.eclipse.core.resources,org.eclipse.ui,org.eclipse.ui.ide,org.eclipse.ui.views,org.eclipse.rse.services,org.eclipse.rse.core,org.eclipse.rse.ui,org.eclipse.rse.subsystems.files.core,org.eclipse.rse.files.ui
Eclipse-LazyStart: true

View file

@ -0,0 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>About</title>
</head>
<body lang="EN-US">
<h2>About This Content</h2>
<p>June 5, 2006</p>
<h3>License</h3>
<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;).
Unless otherwise indicated below, the Content is provided to you under the
terms and conditions of the Eclipse Public License Version 1.0 (&quot;EPL&quot;).
A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html.
For purposes of the EPL, &quot;Program&quot; will mean the Content.
</p>
<p>
If you did not receive this Content directly from the Eclipse Foundation,
the Content is being redistributed by another party (&quot;Redistributor&quot;) and different
terms and conditions may apply to your use of any object code in the Content.
Check the Redistributor’s license that was provided with the Content.
If no such license exists, contact the Redistributor.
Unless otherwise indicated below, the terms and conditions of the EPL still
apply to any source code in the Content and such source code may be obtained
at http://www.eclipse.org.
</p>
</body>
</html>

View file

@ -0,0 +1,22 @@
###############################################################################
# Copyright (c) 2000, 2007 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
source.systemsImportExport.jar = src/
output.systemsImportExport.jar = bin/
bin.includes = plugin.xml,\
systemsImportExport.jar,\
plugin.properties,\
icons/,\
about.html,\
about.properties,\
about.ini,\
wsFeat.gif,\
about.html,\
META-INF/

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 B

View file

@ -0,0 +1,46 @@
###############################################################################
# Copyright (c) 2000, 2007 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
# NLS_MESSAGEFORMAT_NONE
# NLS_ENCODING=UTF-8
# Plugin name
plugin.name = RSE Import/Export
# Remote file import and export wizards
RemoteFileSystemExportWizard.label = Remote file system
RemoteFileSystemExportWizard.description = Export resources to a remote file system
RemoteFileSystemImportWizard.label = Remote file system
RemoteFileSystemImportWizard.description = Import resources from a remote file system
# Remote file export action
RemoteFileExportAction.label = E&xport to Remote File System
RemoteFileExportAction.tooltip = Exports resources to a remote file system based on the selected export description file
# Open remote file export wizard
OpenRemoteFileExport.label = Ope&n Remote File Exporter...
OpenRemoteFileExport.tooltip = Opens the remote file system export wizard based on the selected export description file
# Remote file import action
RemoteFileImportAction.label = Import from Remote File System
RemoteFileImportAction.tooltip = Imports resources from a remote file system based on the selected import description file
# Open remote file import wizard
OpenRemoteFileImport.label = Ope&n Remote File Importer...
OpenRemoteFileImport.tooltip = Opens the remote file system import wizard based on the selected import description file
# Import to project
ImportToProject.label = Import To Project...
ImportToProject.tooltip = Import contents of selected folder to a project
# Export from project
ExportFromProject.label = Export From Project...
ExportFromProject.tooltip = Export contents of project to the selected folder

View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
<extension
point="org.eclipse.ui.importWizards">
</extension>
<extension
point="org.eclipse.ui.popupMenus">
</extension>
<extension
point="org.eclipse.ui.exportWizards">
</extension>
<extension
point="org.eclipse.ui.popupMenus">
</extension>
<extension
point="org.eclipse.ui.popupMenus">
</extension>
</plugin>

View file

@ -0,0 +1,37 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport;
/**
* Interface containing contstants required for import and export.
*/
public interface IRemoteImportExportConstants {
/**
* Remote file import description file extension, "rimpfd".
*/
public static final String REMOTE_FILE_IMPORT_DESCRIPTION_FILE_EXTENSION = "rimpfd"; //$NON-NLS-1$
/**
* An array of import description file extensions.
*/
public static final String[] REMOTE_IMPORT_DESCRIPTION_FILE_EXTENSIONS = { REMOTE_FILE_IMPORT_DESCRIPTION_FILE_EXTENSION };
/**
* Remote file export description file extension, "rexpfd".
*/
public static final String REMOTE_FILE_EXPORT_DESCRIPTION_FILE_EXTENSION = "rexpfd"; //$NON-NLS-1$
/**
* Remote jar export description file extension, "rmtjardesc".
*/
public static final String REMOTE_JAR_EXPORT_DESCRIPTION_FILE_EXTENSION = "rmtjardesc"; //$NON-NLS-1$
/**
* An array of export description file extensions.
*/
public static final String[] REMOTE_EXPORT_DESCRIPTION_FILE_EXTENSIONS = { REMOTE_FILE_EXPORT_DESCRIPTION_FILE_EXTENSION, REMOTE_JAR_EXPORT_DESCRIPTION_FILE_EXTENSION };
}

View file

@ -0,0 +1,93 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
/**
* This class defines a viewer filter that can be used with a selection dialog, e.g. <code>ElementTreeSelectionDialog</code>.
* The viewer filter only allows description files for import/export. Current known extensions are defined
* in class <code>RemoteFileImportExportConstants</code>.
*/
public class RemoteImportExportDescriptionFilesViewerFilter extends ViewerFilter {
/**
* Constant indicating descriptor files for both import and export should be allowed.
*/
public static final int IMPORT_EXPORT = 0;
/**
* Constant indicating that only descriptor files for imports should be allowed.
*/
public static final int IMPORT_ONLY = 1;
/**
* Constant indicating that only descriptor files for exports should be allowed.
*/
public static final int EXPORT_ONLY = 2;
private int mode;
/**
* Constructor.
* @param mode the mode. One of <code>IMPORT_EXPORT</code>, <code>IMPORT_ONLY</code>, or <code>EXPORT_ONLY</code>.
*/
public RemoteImportExportDescriptionFilesViewerFilter(int mode) {
Assert.isLegal((mode == IMPORT_EXPORT) || (mode == IMPORT_ONLY) || (mode == EXPORT_ONLY));
this.mode = mode;
}
/**
* Allows containers and import/export description files.
* @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof IResource) {
IResource resource = (IResource) element;
if (resource.getType() == IResource.FILE) {
String extension = resource.getFileExtension();
if (extension == null || extension.equals("")) { //$NON-NLS-1$
return false;
}
switch (mode) {
case IMPORT_EXPORT:
return (contains(IRemoteImportExportConstants.REMOTE_IMPORT_DESCRIPTION_FILE_EXTENSIONS, extension) || contains(
IRemoteImportExportConstants.REMOTE_EXPORT_DESCRIPTION_FILE_EXTENSIONS, extension));
case IMPORT_ONLY:
return contains(IRemoteImportExportConstants.REMOTE_IMPORT_DESCRIPTION_FILE_EXTENSIONS, extension);
case EXPORT_ONLY:
return contains(IRemoteImportExportConstants.REMOTE_EXPORT_DESCRIPTION_FILE_EXTENSIONS, extension);
// should never be here
default:
return false;
}
} else {
return true;
}
} else {
return false;
}
}
/**
* Returns whether an extension exists in an array of extensions.
* @param extensions an array to extensions.
* @param extension the extension.
* @return <code>true</code> if the extension exists in the array of extensions, <code>false</code> otherwise.
*/
private boolean contains(String[] extensions, String extension) {
for (int i = 0; i < extensions.length; i++) {
if (extensions[i].equals(extension)) {
return true;
}
}
return false;
}
}

View file

@ -0,0 +1,141 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* Overrides <code>ErrorDialog</code> to provide a dialog with
* the image that corresponds to the <code>IStatus</code>.
*
* This behavior should be implemented in the ErrorDialog itself,
* see: 1GJU7TK: ITPUI:WINNT - DCR: ErrorDialog should not always show the error icon
* The class can be removed when the above PR is fixed
*
* @see org.eclipse.core.runtime.IStatus
*/
public class RemoteImportExportProblemDialog extends ErrorDialog {
private Image fImage;
/**
* Creates a problem dialog.
*
* @param parent the shell under which to create this dialog
* @param title the title to use for this dialog,
* or <code>null</code> to indicate that the default title should be used
* @param message the message to show in this dialog,
* or <code>null</code> to indicate that the error's message should be shown
* as the primary message
* @param image the image to be used
* @param status the error to show to the user
* @param displayMask the mask to use to filter the displaying of child items,
* as per <code>IStatus.matches</code>
* @see org.eclipse.core.runtime.IStatus#matches
*/
protected RemoteImportExportProblemDialog(Shell parent, String title, String message, Image image, IStatus status, int displayMask) {
super(parent, title, message, status, displayMask);
fImage = image;
}
/*
* Overrides method declared on Dialog.
*/
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
if (fImage == null) {
return composite;
}
// find the label that contains the image
Control[] kids = composite.getChildren();
int childCount = kids.length;
Label label = null;
int i = 0;
while (i < childCount) {
if (kids[i] instanceof Label) {
label = (Label) kids[i];
if (label.getImage() != null) {
break;
}
}
i++;
}
if (i < childCount && label != null) {
label.setImage(fImage);
}
applyDialogFont(composite);
return composite;
}
/**
* Opens a warning dialog to display the given warning. Use this method if the
* warning object being displayed does not contain child items, or if you
* wish to display all such items without filtering.
*
* @param parent the parent shell of the dialog, or <code>null</code> if none
* @param title the title to use for this dialog,
* or <code>null</code> to indicate that the default title should be used
* @param message the message to show in this dialog,
* or <code>null</code> to indicate that the error's message should be shown
* as the primary message
* @param status the error to show to the user
* @return the code of the button that was pressed that resulted in this dialog
* closing. This will be <code>Dialog.OK</code> if the OK button was
* pressed, or <code>Dialog.CANCEL</code> if this dialog's close window
* decoration or the ESC key was used.
*/
public static int open(Shell parent, String title, String message, IStatus status) {
return open(parent, title, message, status, IStatus.OK | IStatus.INFO | IStatus.WARNING | IStatus.ERROR);
}
/**
* Opens a dialog to display either an error or warning dialog. Use this method if the
* status being displayed contains child items <it>and</it> you wish to
* specify a mask which will be used to filter the displaying of these
* children. The error dialog will only be displayed if there is at
* least one child status matching the mask.
*
* @param parent the parent shell of the dialog, or <code>null</code> if none
* @param title the title to use for this dialog,
* or <code>null</code> to indicate that the default title should be used
* @param message the message to show in this dialog,
* or <code>null</code> to indicate that the error's message should be shown
* as the primary message
* @param status the error to show to the user
* @param displayMask the mask to use to filter the displaying of child items,
* as per <code>IStatus.matches</code>
* @return the code of the button that was pressed that resulted in this dialog
* closing. This will be <code>Dialog.OK</code> if the OK button was
* pressed, or <code>Dialog.CANCEL</code> if this dialog's close window
* decoration or the ESC key was used.
* @see org.eclipse.core.runtime.IStatus#matches
*/
public static int open(Shell parent, String title, String message, IStatus status, int displayMask) {
Image image;
Display display = parent.getDisplay();
if (status == null || status.matches(IStatus.ERROR)) {
image = display.getSystemImage(SWT.ICON_ERROR);
} else if (status.matches(IStatus.WARNING)) {
image = display.getSystemImage(SWT.ICON_WARNING);
} else {
image = display.getSystemImage(SWT.ICON_INFORMATION);
}
ErrorDialog dialog = new RemoteImportExportProblemDialog(parent, title, message, image, status, displayMask);
return dialog.open();
}
}

View file

@ -0,0 +1,37 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport;
import org.eclipse.osgi.util.NLS;
public class RemoteImportExportResources extends NLS {
private static String BUNDLE_NAME = "org.eclipse.rse.files.importexport.RemoteImportExportResources"; //$NON-NLS-1$
public static String IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_TITLE;
public static String IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_MESSAGE;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_ABSOLUTE;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_EXISTING_CONTAINER;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_NO_CONTAINER;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_INVALID_EXTENSION;
public static String IMPORT_EXPORT_ERROR_CREATE_FILES_FAILED;
public static String IMPORT_EXPORT_ERROR_CREATE_FILE_FAILED;
public static String IMPORT_EXPORT_EXPORT_ACTION_DELEGATE_TITLE;
public static String IMPORT_EXPORT_IMPORT_ACTION_DELEGATE_TITLE;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_READ;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_CLOSE;
public static String WizardDataTransfer_existsQuestion;
public static String WizardDataTransfer_overwriteNameAndPathQuestion;
public static String WizardDataTransfer_exceptionMessage;
public static String Question;
static {
// load message values from bundle file
NLS.initializeMessages(BUNDLE_NAME, RemoteImportExportResources.class);
}
}

View file

@ -0,0 +1,39 @@
###############################################################################
# Copyright (c) 2000, 2007 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
# NLS_MESSAGEFORMAT_VAR
# NLS_ENCODING=UTF-8
# Description file messages
IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_TITLE = Save As
IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_MESSAGE = Select location and name for the description
IMPORT_EXPORT_ERROR_DESCRIPTION_ABSOLUTE = Description file path must be absolute (i.e. begins with /)
IMPORT_EXPORT_ERROR_DESCRIPTION_EXISTING_CONTAINER = The description file location must not be an existing container
IMPORT_EXPORT_ERROR_DESCRIPTION_NO_CONTAINER = Container for description file does not exist
IMPORT_EXPORT_ERROR_DESCRIPTION_INVALID_EXTENSION = Description file extension must be ''.{0}''
# Creation failure messages
IMPORT_EXPORT_ERROR_CREATE_FILES_FAILED = Creation of some files failed. See details for additional information.
IMPORT_EXPORT_ERROR_CREATE_FILE_FAILED = File creation failed. See details for additional information.
# Description file error messages
IMPORT_EXPORT_ERROR_DESCRIPTION_READ = Error reading {0}: {1}
IMPORT_EXPORT_ERROR_DESCRIPTION_CLOSE = Error closing description reader for {0}
# Action delegate
IMPORT_EXPORT_EXPORT_ACTION_DELEGATE_TITLE = Remote File Export
IMPORT_EXPORT_IMPORT_ACTION_DELEGATE_TITLE = Remote File Import
#Generic messages
WizardDataTransfer_existsQuestion = ''{0}'' already exists. Would you like to overwrite it?
WizardDataTransfer_overwriteNameAndPathQuestion = Overwrite ''{0}'' in folder ''{1}''?
WizardDataTransfer_exceptionMessage = Error occurred during operation: {0}
Question = Question

View file

@ -0,0 +1,42 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport;
import org.eclipse.core.resources.IFile;
/**
* A runnable class that exports from an export description file. Use this class
* to export in a non-UI thread, by using Display.syncExec() or Display.asyncExec().
*/
public class RemoteImportExportRunnable implements Runnable {
// description file
private IFile file;
private boolean export;
/**
* Constrcutor.
* @param descriptionFile the description file.
* @param export <code>true</code> to export, otherwise <code>false</code>.
*/
public RemoteImportExportRunnable(IFile descriptionFile, boolean export) {
this.file = descriptionFile;
this.export = export;
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
if (export) {
RemoteImportExportUtil.getInstance().exportFromDescriptionFile(file);
}
}
}

View file

@ -0,0 +1,142 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.files.importexport.files.RemoteFileExportActionDelegate;
/**
* Utility class for import and export. A singleton class.
*/
public class RemoteImportExportUtil {
private static RemoteImportExportUtil instance;
/**
* Dummy action. Does nothing.
*/
private class DummyAction extends Action {
/**
* Constructor.
*/
public DummyAction() {
super();
}
}
private RemoteImportExportUtil() {
}
public static RemoteImportExportUtil getInstance() {
if (instance == null) {
instance = new RemoteImportExportUtil();
}
return instance;
}
/**
* Does an export from a description file. The given description file must exist.
* @param descriptionFile the export description file.
*/
public void exportFromDescriptionFile(IFile descriptionFile) {
Assert.isLegal((descriptionFile != null) && descriptionFile.exists());
IFile file = descriptionFile;
String extension = file.getFileExtension();
if (extension == null || extension.equals("")) { //$NON-NLS-1$
return;
}
if (extension.equals(IRemoteImportExportConstants.REMOTE_FILE_EXPORT_DESCRIPTION_FILE_EXTENSION)) {
RemoteFileExportActionDelegate action = new RemoteFileExportActionDelegate();
DummyAction dummy = new DummyAction();
action.selectionChanged(dummy, new StructuredSelection(file));
action.run(dummy);
} else if (extension.equals(IRemoteImportExportConstants.REMOTE_JAR_EXPORT_DESCRIPTION_FILE_EXTENSION)) {
// TODO
// CreateRemoteJarActionDelegate action = new CreateRemoteJarActionDelegate();
// DummyAction dummy = new DummyAction();
// action.selectionChanged(dummy, new StructuredSelection(file));
// action.run(dummy);
}
}
/**
* Helper method for case insensitive file systems. Returns
* an existing resource whose path differs only in case from
* the given path, or null if no such resource exists.
*/
public IResource findExistingResourceVariant(IPath target) {
IWorkspace workspace = SystemBasePlugin.getWorkspace();
// check if local file system is case sensitive
boolean isCaseInsensitive = Platform.getOS().equals(Platform.OS_WIN32);
// if so, we don't need to go any further
if (!isCaseInsensitive) {
return null;
}
IWorkspaceRoot root = workspace.getRoot();
IPath result = root.getFullPath();
IContainer container = root;
int segmentCount = target.segmentCount();
for (int i = 0; i < segmentCount; i++) {
IResource[] children = null;
if (i != 0) {
IResource resource = root.findMember(result);
if ((resource != null) && (resource instanceof IContainer)) {
container = (IContainer) resource;
} else {
return null;
}
}
try {
children = container.members();
} catch (CoreException e) {
SystemBasePlugin.logError("Exception occured trying to get children of " + result, e); //$NON-NLS-1$
}
String name = findVariant(target.segment(i), children);
if (name == null) {
return null;
}
result = result.append(name);
}
return root.findMember(result);
}
/**
* Searches for a variant of the given target in the list,
* that differs only in case. Returns the variant from
* the list if one is found, otherwise returns null.
* @param target the name.
* @param list the list of resources that may have the variant
*/
private String findVariant(String target, IResource[] list) {
if (list == null) {
return null;
}
// go through list
for (int i = 0; i < list.length; i++) {
String name = list[i].getName();
// see if there is a variant, and if so, return it
if (target.equalsIgnoreCase(name)) {
return name;
}
}
return null;
}
}

View file

@ -0,0 +1,20 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
public class Debug {
//execution time switches
public static boolean debug = false;
public static void out(String s) {
if (debug) System.out.println(s);
}
}

View file

@ -0,0 +1,233 @@
package org.eclipse.rse.files.importexport.files;
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.model.AdaptableList;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.model.WorkbenchAdapter;
// Similar to org.eclipse.ui.dialogs.FileSystemElement
// Changes: added getName() method
/**
* Instances of this class represent files or file-like entities (eg.- zip
* file entries) on the local file system. They do not represent resources
* within the workbench. This distinction is made because the representation of
* a file system resource is significantly different from that of a workbench
* resource.
*
* If self represents a collection (eg.- file system directory, zip directory)
* then its icon will be the folderIcon static field. Otherwise (ie.- self
* represents a file system file) self's icon is stored in field "icon", and is
* determined by the extension of the file that self represents.
*
* This class is adaptable, and implements one adapter itself, namely the
* IWorkbenchAdapter adapter used for navigation and display in the workbench.
*/
public class FileSystemElement implements IAdaptable {
private String name;
private Object fileSystemObject;
/* Wait until a child is added to initialize the receiver's lists.
* Doing so minimizes the amount of memory that is allocated when
* a large directory structure is being processed.
*/
private AdaptableList folders = null;
private AdaptableList files = null;
private boolean isDirectory = false;
private FileSystemElement parent;
private final static AdaptableList EMPTY_LIST = new AdaptableList(0);
private WorkbenchAdapter workbenchAdapter = new WorkbenchAdapter() {
/**
* Answer the children property of this element
*/
public Object[] getChildren(Object o) {
return getFolders().getChildren(o);
}
/**
* Returns the parent of this element
*/
public Object getParent(Object o) {
return parent;
}
/**
* Returns an appropriate label for this file system element.
*/
public String getLabel(Object o) {
return name;
}
/**
* Returns an image descriptor for this file system element
*/
public ImageDescriptor getImageDescriptor(Object object) {
if (isDirectory()) {
return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER);
} else {
return PlatformUI.getWorkbench().getEditorRegistry().getImageDescriptor(name);
}
}
};
/**
* Creates a new <code>FileSystemElement</code> and initializes it
* and its parent if applicable.
*
* @param name java.lang.String
*/
public FileSystemElement(String name, FileSystemElement parent, boolean isDirectory) {
this.name = name;
this.parent = parent;
this.isDirectory = isDirectory;
if (parent != null) parent.addChild(this);
}
/**
* Adds the passed child to this object's collection of children.
*
* @param child FileSystemElement
*/
public void addChild(FileSystemElement child) {
if (child.isDirectory()) {
if (folders == null) folders = new AdaptableList(1);
folders.add(child);
} else {
if (files == null) files = new AdaptableList(1);
files.add(child);
}
}
/**
* Returns the adapter
*/
public Object getAdapter(Class adapter) {
if (adapter == IWorkbenchAdapter.class) {
return workbenchAdapter;
}
//defer to the platform
return Platform.getAdapterManager().getAdapter(this, adapter);
}
/**
* Returns the extension of this element's filename. Returns
* The empty string if there is no extension.
*/
public String getFileNameExtension() {
int lastDot = name.lastIndexOf('.');
return lastDot < 0 ? "" : name.substring(lastDot + 1); //$NON-NLS-1$
}
/**
* Answer the files property of this element. Answer an empty list if the
* files property is null.
* This method should not be used to add children
* to the receiver. Use addChild(FileSystemElement) instead.
*/
public AdaptableList getFiles() {
if (files == null) return EMPTY_LIST;
return files;
}
/**
* Returns the file system object property of this element
*
* @return the file system object
*/
public Object getFileSystemObject() {
return fileSystemObject;
}
/**
* Returns a list of the folders that are immediate children
* of this folder. Answer an empty list if the folders property is null.
* This method should not be used to add children
* to the receiver. Use addChild(FileSystemElement) instead.
*/
public AdaptableList getFolders() {
if (folders == null) return EMPTY_LIST;
return folders;
}
/**
* Returns the name.
*/
public String getName() {
return name;
}
/**
* Return the parent of this element.
*
* @return the parent file system element, or <code>null</code> if this is the root
*/
public FileSystemElement getParent() {
return this.parent;
}
/**
* Returns true if this element represents a directory, and false
* otherwise.
*/
public boolean isDirectory() {
return isDirectory;
}
/**
* Removes a sub-folder from this file system element.
*/
public void removeFolder(FileSystemElement child) {
if (folders == null) return;
folders.remove(child);
child.setParent(null);
}
/**
* Set the file system object property of this element
*
* @param value the file system object
*/
public void setFileSystemObject(Object value) {
fileSystemObject = value;
}
/**
* Sets the parent of this file system element.
*/
public void setParent(FileSystemElement element) {
parent = element;
}
/**
* For debugging purposes only.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
if (isDirectory()) {
buf.append("Folder(");//$NON-NLS-1$
} else {
buf.append("File(");//$NON-NLS-1$
}
buf.append(name).append(")");//$NON-NLS-1$
if (!isDirectory()) {
return buf.toString();
}
buf.append(" folders: ");//$NON-NLS-1$
buf.append(folders);
buf.append(" files: ");//$NON-NLS-1$
buf.append(files);
return buf.toString();
}
}

View file

@ -0,0 +1,101 @@
package org.eclipse.rse.files.importexport.files;
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
// Similar to org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider
// Changes marked with "IFS:" comments.
/**
* This class provides information regarding the structure and
* content of specified file system File objects.
*/
public class FileSystemStructureProvider implements IImportStructureProvider {
/**
* Holds a singleton instance of this class.
*/
public final static FileSystemStructureProvider INSTANCE = new FileSystemStructureProvider();
/**
* Creates an instance of <code>FileSystemStructureProvider</code>.
*/
public FileSystemStructureProvider() {
super();
}
/* (non-Javadoc)
* Method declared on IImportStructureProvider
*/
public List getChildren(Object element) {
List result = new ArrayList(0);
try {
String[] children = ((File) element).list();
int childrenLength = children == null ? 0 : children.length;
result = new ArrayList(childrenLength);
long start = System.currentTimeMillis();
// String p=((UniFilePlus)element).getAbsolutePath()+"/"; //$NON-NLS-1$
// IHost sysC=((UniFilePlus) element).remoteFile.getSystemConnection();
IRemoteFile[] childIRemoteFiles = ((UniFilePlus) element).listIRemoteFiles();
for (int i = 0; i < childrenLength; i++)
result.add(new UniFilePlus(childIRemoteFiles[i]));
Debug.out("Expanding [" + ((File) element).getPath() + "] took in (ms): " + (System.currentTimeMillis() - start)); //$NON-NLS-1$ //$NON-NLS-2$
} catch (Exception e) {
// Probably caused by IFS authority problem
// ignore for now
}
return result;
}
/* (non-Javadoc)
* Method declared on IImportStructureProvider
*/
public InputStream getContents(Object element) {
try {
return new FileInputStream((File) element);
} catch (FileNotFoundException e) {
return null;
}
}
/* (non-Javadoc)
* Method declared on IImportStructureProvider
*/
public String getFullPath(Object element) {
return ((File) element).getPath();
}
/* (non-Javadoc)
* Method declared on IImportStructureProvider
*/
public String getLabel(Object element) {
//Get the name - if it is empty then return the path as it is a file root
File file = (File) element;
String name = file.getName();
if (name == null || name.length() == 0)
return file.getPath();
else
return name;
}
/* (non-Javadoc)
* Method declared on IImportStructureProvider
*/
public boolean isFolder(Object element) {
return ((File) element).isDirectory();
}
}

View file

@ -0,0 +1,64 @@
package org.eclipse.rse.files.importexport.files;
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.io.InputStream;
import java.util.List;
// Similar to org.eclipse.ui.wizards.datatransfer.IImportStructureProvider
// Basically unchanged.
/**
* Interface which can provide structure and content information
* for an element (for example, a file system element).
* Used by the import wizards to abstract the commonalities
* between importing from the file system and importing from an archive.
*/
public interface IImportStructureProvider {
/**
* Returns a collection with the children of the specified structured element.
*/
List getChildren(Object element);
/**
* Returns the contents of the specified structured element, or
* <code>null</code> if there is a problem determining the element's
* contents.
*
* @param element a structured element
* @return the contents of the structured element, or <code>null</code>
*/
InputStream getContents(Object element);
/**
* Returns the full path of the specified structured element.
*
* @param element a structured element
* @return the display label of the structured element
*/
String getFullPath(Object element);
/**
* Returns the display label of the specified structured element.
*
* @param element a structured element
* @return the display label of the structured element
*/
String getLabel(Object element);
/**
* Returns a boolean indicating whether the passed structured element represents
* a container element (as opposed to a leaf element).
*
* @return boolean
* @param element java.lang.Object
*/
boolean isFolder(Object element);
}

View file

@ -0,0 +1,25 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
/**
* An interface for remote file export description reader.
*/
public interface IRemoteFileExportDescriptionReader {
public void read(RemoteFileExportData exportData) throws CoreException;
public void close() throws CoreException;
public IStatus getStatus();
}

View file

@ -0,0 +1,25 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
/**
* An interface for remote file export description writer.
*/
public interface IRemoteFileExportDescriptionWriter {
public void write(RemoteFileExportData exportData) throws CoreException;
public void close() throws CoreException;
public IStatus getStatus();
}

View file

@ -0,0 +1,25 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
/**
* An interface for remote file import description reader.
*/
public interface IRemoteFileImportDescriptionReader {
public void read(RemoteFileImportData importData) throws CoreException;
public void close() throws CoreException;
public IStatus getStatus();
}

View file

@ -0,0 +1,25 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
/**
* An interface for remote file import description writer.
*/
public interface IRemoteFileImportDescriptionWriter {
public void write(RemoteFileImportData importData) throws CoreException;
public void close() throws CoreException;
public IStatus getStatus();
}

View file

@ -0,0 +1,99 @@
package org.eclipse.rse.files.importexport.files;
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.ui.model.AdaptableList;
// Similar to org.eclipse.ui.wizards.datatransfer.MinimizedFileSystemElement
// Changes marked with "IFS:" comments.
/**
* The <code>MinimizedFileSystemElement</code> is a <code>FileSystemElement</code> that knows
* if it has been populated or not.
*/
// IFS: made class public
public class MinimizedFileSystemElement extends FileSystemElement {
private boolean populated = false;
/**
* Create a <code>MinimizedFileSystemElement</code> with the supplied name and parent.
* @param name the name of the file element this represents
* @param parent the containing parent
* @param isDirectory indicated if this could have children or not
*/
public MinimizedFileSystemElement(String name, FileSystemElement parent, boolean isDirectory) {
super(name, parent, isDirectory);
}
/**
* Returns a list of the files that are immediate children. Use the supplied provider
* if it needs to be populated.
* of this folder.
*/
public AdaptableList getFiles(IImportStructureProvider provider) {
if (!populated) populate(provider);
return super.getFiles();
}
/**
* Returns a list of the folders that are immediate children. Use the supplied provider
* if it needs to be populated.
* of this folder.
*/
public AdaptableList getFolders(IImportStructureProvider provider) {
if (!populated) populate(provider);
return super.getFolders();
}
/**
* Return whether or not population has happened for the receiver.
*/
// IFS: made method public
public boolean isPopulated() {
return this.populated;
}
/**
* Return whether or not population has not happened for the receiver.
*/
boolean notPopulated() {
return !this.populated;
}
/**
* Populate the files and folders of the receiver using the suppliec structure provider.
* @param provider org.eclipse.ui.wizards.datatransfer.IImportStructureProvider
*/
private void populate(IImportStructureProvider provider) {
Object fileSystemObject = getFileSystemObject();
List children = provider.getChildren(fileSystemObject);
if (children == null) children = new ArrayList(1);
Iterator childrenEnum = children.iterator();
while (childrenEnum.hasNext()) {
Object child = childrenEnum.next();
String elementLabel = provider.getLabel(child);
//Create one level below
MinimizedFileSystemElement result = new MinimizedFileSystemElement(elementLabel, this, provider.isFolder(child));
result.setFileSystemObject(child);
}
setPopulated();
}
/**
* Set whether or not population has happened for the receiver to true.
*/
public void setPopulated() {
this.populated = true;
}
}

View file

@ -0,0 +1,128 @@
package org.eclipse.rse.files.importexport.files;
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.rse.importexport.SystemImportExportResources;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.ui.wizards.AbstractSystemWizard;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
/**
* Standard workbench wizard for exporting resources from the workspace
* to the local file system.
* <p>
* This class may be instantiated and used without further configuration;
* this class is not intended to be subclassed.
* </p>
* <p>
* Example:
* <pre>
* IWizard wizard = new RemoteExportWizard();
* wizard.init(workbench, selection);
* WizardDialog dialog = new WizardDialog(shell, wizard);
* dialog.open();
* </pre>
* During the call to <code>open</code>, the wizard dialog is presented to the
* user. When the user hits Finish, the user-selected workspace resources
* are exported to the user-specified location in the local file system,
* the dialog closes, and the call to <code>open</code> returns.
* </p>
*/
public class RemoteExportWizard extends AbstractSystemWizard implements IExportWizard {
private IStructuredSelection selection;
private RemoteExportWizardPage1 mainPage;
private RemoteFileExportData exportData;
private boolean initializeFromExportData;
/**
* Creates a wizard for exporting workspace resources to the local file system.
*/
public RemoteExportWizard() {
IDialogSettings workbenchSettings = RSEUIPlugin.getDefault().getDialogSettings();
IDialogSettings section = workbenchSettings.getSection("RemoteExportWizard"); //$NON-NLS-1$
if (section == null) section = workbenchSettings.addNewSection("RemoteExportWizard"); //$NON-NLS-1$
setDialogSettings(section);
}
/* (non-Javadoc)
* Method declared on IWizard.
*/
public void addPages() {
mainPage = new RemoteExportWizardPage1(selection);
addPage(mainPage);
}
/**
* Returns the image descriptor with the given relative path.
*/
private ImageDescriptor getImageDescriptor(String relativePath) {
String iconPath = "icons/full/"; //$NON-NLS-1$
return RSEUIPlugin.getDefault().getPluginImage(iconPath + relativePath);
}
/* (non-Javadoc)
* Method declared on IWorkbenchWizard.
*/
public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
// make it the current selection by default but look it up otherwise
this.selection = currentSelection;
if (currentSelection.isEmpty() && workbench.getActiveWorkbenchWindow() != null) {
IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();
if (page != null) {
IEditorPart currentEditor = page.getActiveEditor();
if (currentEditor != null) {
Object selectedResource = currentEditor.getEditorInput().getAdapter(IResource.class);
if (selectedResource != null) selection = new StructuredSelection(selectedResource);
}
}
}
setInitializeFromExportData(false);
setWindowTitle(SystemImportExportResources.RESID_FILEEXPORT_TITLE);
setDefaultPageImageDescriptor(getImageDescriptor("wizban/export_wiz.gif")); //$NON-NLS-1$
setNeedsProgressMonitor(true);
}
public void init(IWorkbench workbench, RemoteFileExportData exportData) {
this.selection = new StructuredSelection(exportData.getElements().toArray());
this.exportData = exportData;
setInitializeFromExportData(true);
setWindowTitle(SystemImportExportResources.RESID_FILEEXPORT_TITLE);
setDefaultPageImageDescriptor(getImageDescriptor("wizban/export_wiz.gif")); //$NON-NLS-1$
setNeedsProgressMonitor(true);
}
protected void setInitializeFromExportData(boolean init) {
this.initializeFromExportData = init;
}
public boolean getInitializeFromExportData() {
return initializeFromExportData;
}
public RemoteFileExportData getExportData() {
return exportData;
}
/**
* Method declared on IWizard.
*/
public boolean performFinish() {
return mainPage.finish();
}
}

View file

@ -0,0 +1,867 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.files.importexport.RemoteImportExportResources;
import org.eclipse.rse.files.importexport.RemoteImportExportUtil;
import org.eclipse.rse.files.ui.actions.SystemSelectRemoteFolderAction;
import org.eclipse.rse.importexport.SystemImportExportResources;
import org.eclipse.rse.services.clientserver.messages.SystemMessage;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
import org.eclipse.rse.ui.ISystemMessages;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.ui.SystemWidgetHelpers;
import org.eclipse.rse.ui.messages.SystemMessageDialog;
import org.eclipse.rse.ui.messages.SystemMessageLine;
import org.eclipse.rse.ui.wizards.ISystemWizardPage;
import org.eclipse.swt.SWT;
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.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.WizardExportResourcesPage;
/**
* Page 1 of the base resource export-to-file-system Wizard
*
* 040510 AR Fix "Create folder" question. Previous fix changed the way we were
* asking user if they wanted target folder created, to use RSE
* widgets. But introduced error.
*/
class RemoteExportWizardPage1 extends WizardExportResourcesPage implements Listener, ISystemWizardPage {
private Object destinationFolder = null;
private String helpId;
private Composite parentComposite;
private SystemMessageLine msgLine;
private SystemMessage pendingMessage, pendingErrorMessage;
// widgets
private Combo destinationNameField;
private Button destinationBrowseButton;
protected Button overwriteExistingFilesCheckbox;
protected Button createDirectoryStructureButton;
protected Button createSelectionOnlyButton;
protected Button saveSettingsButton;
protected Label descFilePathLabel;
protected Text descFilePathField;
protected Button descFileBrowseButton;
// input object
protected Object inputObject = null;
// constants
private static final int MY_SIZING_TEXT_FIELD_WIDTH = 250;
// dialog store id constants
private static final String STORE_DESTINATION_NAMES_ID = "RemoteExportWizard.STORE_DESTINATION_NAMES_ID"; //$NON-NLS-1$
private static final String STORE_OVERWRITE_EXISTING_FILES_ID = "RemoteExportWizard.STORE_OVERWRITE_EXISTING_FILES_ID"; //$NON-NLS-1$
private static final String STORE_CREATE_STRUCTURE_ID = "RemoteExportWizard.STORE_CREATE_STRUCTURE_ID"; //$NON-NLS-1$
private static final String STORE_CREATE_DESCRIPTION_FILE_ID = "RemoteExportWizard.STORE_CREATE_DESCRIPTION_FILE_ID"; //$NON-NLS-1$
private static final String STORE_DESCRIPTION_FILE_NAME_ID = "RemoteExportWizard.STORE_DESCRIPTION_FILE_NAME_ID"; //$NON-NLS-1$
//messages
private static final SystemMessage DESTINATION_EMPTY_MESSAGE = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_DESTINATION_EMPTY); //UniversalSystemPlugin.getString("IFSexport.destinationEmpty");
/**
* Create an instance of this class
*/
protected RemoteExportWizardPage1(String name, IStructuredSelection selection) {
super(name, selection);
setInputObject(selection);
}
/**
* Create an instance of this class
*/
public RemoteExportWizardPage1(IStructuredSelection selection) {
this("fileSystemExportPage1", selection); //$NON-NLS-1$
setTitle(SystemImportExportResources.RESID_FILEEXPORT_PAGE1_TITLE);
setDescription(SystemImportExportResources.RESID_FILEEXPORT_PAGE1_DESCRIPTION);
}
/**
* Add the passed value to self's destination widget's history
*
* @param value java.lang.String
*/
protected void addDestinationItem(String value) {
destinationNameField.add(value);
}
/** (non-Javadoc)
* Method declared on IDialogPage.
*/
public void createControl(Composite parent) {
parentComposite = new Composite(parent, SWT.NONE);
parentComposite.setLayout(new GridLayout(1, false));
parentComposite.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
super.createControl(parentComposite);
msgLine = new SystemMessageLine(parentComposite);
msgLine.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
if (pendingMessage != null) setMessage(pendingMessage);
if (pendingErrorMessage != null) setErrorMessage(pendingErrorMessage);
giveFocusToDestination();
SystemWidgetHelpers.setWizardPageMnemonics(parentComposite);
if (helpId != null) {
SystemWidgetHelpers.setHelp(parentComposite, helpId);
} else {
SystemWidgetHelpers.setHelp(parentComposite, RSEUIPlugin.HELPPREFIX + "import_context"); //$NON-NLS-1$
}
setControl(parentComposite);
// super.createControl(parent);
// parentComposite = parent;
// giveFocusToDestination();
// SystemWidgetHelpers.setHelp(getControl(), RSEUIPlugin.HELPPREFIX + "export_context");
// Control c = getControl();
// if (c instanceof Composite)
// {
// SystemWidgetHelpers.setWizardPageMnemonics((Composite)c);
// parentComposite = (Composite)c;
// if (helpId != null)
// SystemWidgetHelpers.setHelp(parentComposite, helpId);
// }
// else if (c instanceof Button)
// {
// Mnemonics ms = new Mnemonics();
// ms.setMnemonic((Button)c);
// }
// configureMessageLine();
}
/**
* Create the export destination specification widgets
*
* @param parent org.eclipse.swt.widgets.Composite
*/
protected void createDestinationGroup(Composite parent) {
// destination specification group
Composite destinationSelectionGroup = SystemWidgetHelpers.createComposite(parent, 3);
((GridData) destinationSelectionGroup.getLayoutData()).verticalAlignment = GridData.FILL;
destinationNameField = SystemWidgetHelpers.createLabeledReadonlyCombo(destinationSelectionGroup, null, SystemImportExportResources.RESID_FILEEXPORT_DESTINATION_LABEL,
SystemImportExportResources.RESID_FILEEXPORT_DESTINATION_TOOLTIP);
((GridData) destinationNameField.getLayoutData()).widthHint = MY_SIZING_TEXT_FIELD_WIDTH;
((GridData) destinationNameField.getLayoutData()).grabExcessHorizontalSpace = true;
destinationNameField.addListener(SWT.Modify, this);
destinationNameField.addListener(SWT.Selection, this);
// destination browse button
destinationBrowseButton = SystemWidgetHelpers.createPushButton(destinationSelectionGroup, null, SystemImportExportResources.RESID_FILEEXPORT_DESTINATION_BROWSE_LABEL,
SystemImportExportResources.RESID_FILEEXPORT_DESTINATION_BROWSE_TOOLTIP);
((GridData) destinationBrowseButton.getLayoutData()).grabExcessHorizontalSpace = false;
destinationBrowseButton.addListener(SWT.Selection, this);
new Label(parent, SWT.NONE); // vertical spacer
}
/**
* Create the export options specification widgets.
* @param optionsGroup the group into which the option buttons will be placed
*/
protected void createOptionsGroupButtons(Group optionsGroup) {
overwriteExistingFilesCheckbox = SystemWidgetHelpers.createCheckBox(optionsGroup, 1, null, SystemImportExportResources.RESID_FILEEXPORT_OPTION_OVERWRITE_LABEL,
SystemImportExportResources.RESID_FILEEXPORT_OPTION_OVERWRITE_TOOLTIP);
createDirectoryStructureButton = SystemWidgetHelpers.createRadioButton(optionsGroup, null, SystemImportExportResources.RESID_FILEEXPORT_OPTION_CREATEALL_LABEL,
SystemImportExportResources.RESID_FILEEXPORT_OPTION_CREATEALL_TOOLTIP);
createSelectionOnlyButton = SystemWidgetHelpers.createRadioButton(optionsGroup, null, SystemImportExportResources.RESID_FILEEXPORT_OPTION_CREATESEL_LABEL,
SystemImportExportResources.RESID_FILEEXPORT_OPTION_CREATESEL_TOOLTIP);
createSelectionOnlyButton.setSelection(true);
Composite comp = SystemWidgetHelpers.createComposite(optionsGroup, 3);
GridLayout layout = new GridLayout();
layout.numColumns = 3;
layout.marginWidth = 0;
comp.setLayout(layout);
comp.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
saveSettingsButton = SystemWidgetHelpers.createCheckBox(comp, 3, null, SystemImportExportResources.RESID_FILEEXPORT_OPTION_SETTINGS_LABEL,
SystemImportExportResources.RESID_FILEEXPORT_OPTION_SETTINGS_TOOLTIP);
saveSettingsButton.addListener(SWT.Selection, this);
descFilePathLabel = new Label(comp, SWT.NONE);
descFilePathLabel.setText(SystemImportExportResources.RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_LABEL);
GridData data = new GridData();
descFilePathLabel.setLayoutData(data);
descFilePathField = new Text(comp, SWT.SINGLE | SWT.BORDER);
descFilePathField.setToolTipText(SystemImportExportResources.RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_PATH_TOOLTIP);
data = new GridData();
data.horizontalAlignment = GridData.HORIZONTAL_ALIGN_FILL;
data.grabExcessHorizontalSpace = true;
data.widthHint = convertWidthInCharsToPixels(80);
descFilePathField.setLayoutData(data);
descFilePathField.addListener(SWT.Modify, this);
descFileBrowseButton = SystemWidgetHelpers.createPushButton(comp, null, SystemImportExportResources.RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_BROWSE_LABEL,
SystemImportExportResources.RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_BROWSE_TOOLTIP);
descFileBrowseButton.addListener(SWT.Selection, this);
}
/**
* @see org.eclipse.ui.dialogs.WizardExportResourcesPage#setupBasedOnInitialSelections()
*/
protected void setupBasedOnInitialSelections() {
Object input = getInputObject();
boolean allResource = true;
// ensure initial input, i.e. selection, comprises of IResources only
if ((input != null) && (input instanceof IStructuredSelection)) {
IStructuredSelection sel = (IStructuredSelection) input;
if (sel.size() > 0) {
Iterator z = sel.iterator();
while (z.hasNext()) {
Object obj = z.next();
if (!(obj instanceof IResource)) {
allResource = false;
break;
}
}
} else {
allResource = false;
}
} else {
allResource = false;
}
// if selections are all resources, call super method to setup
if (allResource) {
super.setupBasedOnInitialSelections();
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.dialogs.WizardDataTransferPage#updateWidgetEnablements()
*/
protected void updateWidgetEnablements() {
boolean isSaveSettings = isSaveSettings();
descFilePathLabel.setEnabled(isSaveSettings);
descFilePathField.setEnabled(isSaveSettings);
descFileBrowseButton.setEnabled(isSaveSettings);
}
/**
* Attempts to ensure that the specified directory exists on the local file system.
* Answers a boolean indicating success.
*
* @return boolean
* @param directory java.io.File
*/
protected boolean ensureDirectoryExists(File directory) {
if (!directory.exists()) {
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_TARGET_EXISTS);
msg.makeSubstitution(directory.getAbsolutePath());
SystemMessageDialog dlg = new SystemMessageDialog(getContainer().getShell(), msg);
if (!dlg.openQuestionNoException()) return false;
if (!directory.mkdirs()) {
msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_CREATE_FOLDER_FAILED);
msg.makeSubstitution(directory.getAbsolutePath());
setErrorMessage(msg);
giveFocusToDestination();
return false;
}
}
return true;
}
/**
* If the target for export does not exist then attempt to create it.
* Answer a boolean indicating whether the target exists (ie.- if it
* either pre-existed or this method was able to create it)
*
* @return boolean
*/
protected boolean ensureTargetIsValid(File targetDirectory) {
if (targetDirectory.exists() && !targetDirectory.isDirectory()) {
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_SOURCE_IS_FILE);
msg.makeSubstitution(targetDirectory.getAbsolutePath());
setErrorMessage(msg);
giveFocusToDestination();
return false;
}
return ensureDirectoryExists(targetDirectory);
}
/**
* Set up and execute the passed Operation. Answer a boolean indicating success.
*
* @return boolean
*/
protected boolean executeExportOperation(RemoteFileExportOperation op) {
try {
getContainer().run(true, true, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) { // Display error dialog if exception is NullPointer, assume this means
// communication failure. See RemoteFileExportOperation.exportFile()
if (!NullPointerException.class.isInstance(e.getTargetException())) {
displayErrorDialog(e.getTargetException());
return false;
}
} catch (Exception e) {
displayErrorDialog(e.getMessage());
return false;
}
IStatus status = op.getStatus();
if (!status.isOK()) {
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_FAILED);
msg.makeSubstitution(status);
SystemMessageDialog dlg = new SystemMessageDialog(getContainer().getShell(), msg);
dlg.openWithDetails();
return false;
}
return true;
}
/**
* The Finish button was pressed. Try to do the required work now and answer
* a boolean indicating success. If false is returned then the wizard will
* not close.
*
* @return boolean
*/
public boolean finish() {
clearMessage();
clearErrorMessage();
boolean ret = false;
setDestinationValue(destinationNameField.getText().trim());
if (Utilities.isConnectionValid(destinationNameField.getText().trim(), getShell()) && isDestinationFolder()) {
if (!ensureTargetIsValid((File) destinationFolder)) return false;
List resourcesToExport = getWhiteCheckedResources();
//Save dirty editors if possible but do not stop if not all are saved
saveDirtyEditors();
// about to invoke the operation so save our state
saveWidgetValues();
if (resourcesToExport.size() > 0) {
// export data
RemoteFileExportData data = new RemoteFileExportData();
data.setElements(resourcesToExport);
data.setCreateDirectoryStructure(createDirectoryStructureButton.getSelection());
data.setCreateSelectionOnly(createSelectionOnlyButton.getSelection());
data.setOverWriteExistingFiles(overwriteExistingFilesCheckbox.getSelection());
data.setSaveSettings(saveSettingsButton.getSelection());
data.setDescriptionFilePath(getDescriptionLocation());
data.setDestination(getDestinationValue());
// execute export
ret = executeExportOperation(new RemoteFileExportOperation(data, this));
return ret;
}
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_NONE_SELECTED);
setErrorMessage(msg);
return false;
}
return false;
}
/**
* Gets the destination.
* @return the desstionation.
*/
protected String getDestinationValue() {
return destinationNameField.getText().trim();
}
/**
* Gets the description.
* @return the description.
*/
protected String getDescriptionLocation() {
return descFilePathField.getText().trim();
}
/**
* Returns whether the settings should be saved.
* @return whether settings should be saved.
*/
protected boolean isSaveSettings() {
return saveSettingsButton.getSelection();
}
/**
* Set the current input focus to self's destination entry field
*/
protected void giveFocusToDestination() {
destinationNameField.setFocus();
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDestinationBrowseButtonPressed() {
SystemSelectRemoteFolderAction action = new SystemSelectRemoteFolderAction(this.getShell());
action.setShowNewConnectionPrompt(true);
action.setShowPropertySheet(true, false);
action.run();
IRemoteFile folder = action.getSelectedFolder();
if (folder != null) {
destinationFolder = new UniFilePlus(folder);
setDestinationValue(Utilities.getAsString((UniFilePlus) destinationFolder));
}
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from.
*/
protected void handleDescriptionFileBrowseButtonPressed() {
SaveAsDialog dialog = new SaveAsDialog(getContainer().getShell());
dialog.create();
dialog.getShell().setText(RemoteImportExportResources.IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_TITLE);
dialog.setMessage(RemoteImportExportResources.IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_MESSAGE);
dialog.setOriginalFile(createFileHandle(new Path(getDescriptionLocation())));
if (dialog.open() == Window.OK) {
IPath path = dialog.getResult();
path = path.removeFileExtension().addFileExtension(Utilities.EXPORT_DESCRIPTION_EXTENSION);
descFilePathField.setText(path.toString());
}
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return SystemBasePlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Handle all events and enablements for widgets in this page
* @param e Event
*/
public void handleEvent(Event e) {
Widget source = e.widget;
if (source == destinationBrowseButton) {
handleDestinationBrowseButtonPressed();
} else if (source == descFileBrowseButton) {
handleDescriptionFileBrowseButtonPressed();
}
updateWidgetEnablements();
updatePageCompletion();
}
/**
* Hook method for saving widget values for restoration by the next instance
* of this class.
*/
protected void internalSaveWidgetValues() {
// update directory names history
IDialogSettings settings = getDialogSettings();
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);
// options
settings.put(STORE_OVERWRITE_EXISTING_FILES_ID, overwriteExistingFilesCheckbox.getSelection());
settings.put(STORE_CREATE_STRUCTURE_ID, createDirectoryStructureButton.getSelection());
settings.put(STORE_CREATE_DESCRIPTION_FILE_ID, isSaveSettings());
settings.put(STORE_DESCRIPTION_FILE_NAME_ID, getDescriptionLocation());
}
}
/**
* Method will return boolean value, will issue error if destination is
* null
*/
protected boolean isDestinationFolder() {
boolean ret = destinationFolder != null;
if (!ret) {
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_IMPORT_EXPORT_UNABLE_TO_USE_CONNECTION);
SystemMessageDialog.show(getShell(), msg);
}
return ret;
}
/**
* Hook method for restoring widget values to the values that they held
* last time this wizard was used to completion.
*/
protected void restoreWidgetValues() {
IDialogSettings settings = getDialogSettings();
if (settings != null) {
// destination chosen on previous export
String lastDestination = null;
String[] directoryNames = settings.getArray(STORE_DESTINATION_NAMES_ID);
if (directoryNames != null) {
for (int i = 0; i < directoryNames.length; i++) {
// because of the way we add destination items to history, the
// destination for the previous export would be first
if (i == 0) {
lastDestination = directoryNames[i];
}
addDestinationItem(directoryNames[i]);
}
}
RemoteExportWizard parentWizard = (RemoteExportWizard) getWizard();
boolean isInitializingFromExportData = parentWizard.getInitializeFromExportData();
// options
// no export data to initialize from, so prefill from previous export
if (!isInitializingFromExportData) {
overwriteExistingFilesCheckbox.setSelection(settings.getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID));
boolean createDirectories = settings.getBoolean(STORE_CREATE_STRUCTURE_ID);
createDirectoryStructureButton.setSelection(createDirectories);
createSelectionOnlyButton.setSelection(!createDirectories);
boolean saveSettings = settings.getBoolean(STORE_CREATE_DESCRIPTION_FILE_ID);
saveSettingsButton.setSelection(saveSettings);
String descFilePathStr = settings.get(STORE_DESCRIPTION_FILE_NAME_ID);
if (descFilePathStr == null) {
descFilePathStr = ""; //$NON-NLS-1$
}
descFilePathField.setText(descFilePathStr);
// select previous export destination
if (lastDestination != null) {
setDestinationValue(lastDestination);
}
}
// initialize from export data
else {
RemoteFileExportData data = parentWizard.getExportData();
overwriteExistingFilesCheckbox.setSelection(data.isOverWriteExistingFiles());
createDirectoryStructureButton.setSelection(data.isCreateDirectoryStructure());
createSelectionOnlyButton.setSelection(data.isCreateSelectionOnly());
saveSettingsButton.setSelection(data.isSaveSettings());
String descFilePathStr = data.getDescriptionFilePath();
if (descFilePathStr == null) {
descFilePathStr = ""; //$NON-NLS-1$
}
descFilePathField.setText(descFilePathStr);
String destinationPath = data.getDestination();
if (destinationPath != null) {
setDestinationValue(destinationPath);
}
}
}
// check if there was an initial selection
// if it is a remote directory, then set the absolute path in the source name field
Object initSelection = getInputObject();
if ((initSelection != null) && (initSelection instanceof IStructuredSelection)) {
IStructuredSelection sel = (IStructuredSelection) initSelection;
if (sel.size() == 1) {
Object theSel = sel.getFirstElement();
if (theSel instanceof IRemoteFile) {
IRemoteFile file = (IRemoteFile) theSel;
// set source name if the input is a folder
if (file.isDirectory()) {
destinationFolder = new UniFilePlus(file);
setDestinationValue(Utilities.getAsString((UniFilePlus) destinationFolder));
}
}
}
}
}
/**
* Set the contents of the receivers destination specification widget to
* the passed value
*
*/
protected void setDestinationValue(String path) {
if (path.length() > 0) {
String[] currentItems = destinationNameField.getItems();
int selectionIndex = -1;
for (int i = 0; i < currentItems.length && selectionIndex < 0; i++) {
if (currentItems[i].equals(path)) selectionIndex = i;
}
if (selectionIndex < 0) {
// need to add a new one.
int oldLength = currentItems.length;
String[] newItems = new String[oldLength + 1];
System.arraycopy(currentItems, 0, newItems, 0, oldLength);
newItems[oldLength] = path;
destinationNameField.setItems(newItems);
selectionIndex = oldLength;
} else {
}
destinationNameField.select(selectionIndex);
}
destinationFolder = null; // clear destination
IHost conn = Utilities.parseForSystemConnection(path);
if (conn != null) {
IRemoteFile rf = Utilities.parseForIRemoteFile(path);
if (rf != null) destinationFolder = new UniFilePlus(rf);
}
}
/**
* Answer a boolean indicating whether the receivers destination specification
* widgets currently all contain valid values.
*/
protected boolean validateDestinationGroup() {
String destinationValue = getDestinationValue();
if (destinationValue.length() == 0) {
setMessage(DESTINATION_EMPTY_MESSAGE);
return false;
}
String conflictingContainer = getConflictingContainerNameFor(destinationValue);
if (conflictingContainer != null) {
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_DESTINATION_CONFLICTING);
msg.makeSubstitution(conflictingContainer);
setErrorMessage(msg);
giveFocusToDestination();
return false;
}
return true;
}
/**
* @see org.eclipse.ui.dialogs.WizardDataTransferPage#validateOptionsGroup()
*/
protected boolean validateOptionsGroup() {
if (isSaveSettings()) {
IPath location = new Path(getDescriptionLocation());
// if location is empty, no error message, but it's not valid
if (location.toString().length() == 0) {
setErrorMessage((String) null);
return false;
}
// location must start with '/'
if (!location.toString().startsWith("/")) { //$NON-NLS-1$
setErrorMessage(RemoteImportExportResources.IMPORT_EXPORT_ERROR_DESCRIPTION_ABSOLUTE);
return false;
}
// find the resource, including a variant if any
IResource resource = findResource(location);
// if resource is not a file, it must be a container. So location is pointing to a container, which is an error
if (resource != null && resource.getType() != IResource.FILE) {
setErrorMessage(RemoteImportExportResources.IMPORT_EXPORT_ERROR_DESCRIPTION_EXISTING_CONTAINER);
return false;
}
// get the resource (or any variant of it) after removing the last segment
// this gets the parent resource
resource = findResource(location.removeLastSegments(1));
// if parent resource does not exist, or if it is a file, then it is not valid
if (resource == null || resource.getType() == IResource.FILE) {
setErrorMessage(RemoteImportExportResources.IMPORT_EXPORT_ERROR_DESCRIPTION_NO_CONTAINER);
return false;
}
// get the file extension
String fileExtension = location.getFileExtension();
// ensure that file extension is valid
if (fileExtension == null || !fileExtension.equals(Utilities.EXPORT_DESCRIPTION_EXTENSION)) {
setErrorMessage(MessageFormat.format(RemoteImportExportResources.IMPORT_EXPORT_ERROR_DESCRIPTION_INVALID_EXTENSION, new Object[] { Utilities.EXPORT_DESCRIPTION_EXTENSION }));
return false;
}
}
return true;
}
/**
* Returns the resource for the specified path.
*
* @param path the path for which the resource should be returned
* @return the resource specified by the path or <code>null</code>
*/
protected IResource findResource(IPath path) {
IWorkspace workspace = SystemBasePlugin.getWorkspace();
// validate path
IStatus result = workspace.validatePath(path.toString(), IResource.ROOT | IResource.PROJECT | IResource.FOLDER | IResource.FILE);
// if path valid
if (result.isOK()) {
// get the workspace root
IWorkspaceRoot root = workspace.getRoot();
// see if path exists. If it does, return the resource at the path
if (root.exists(path)) {
return root.findMember(path);
}
// see if a variant of the path exists
else {
// look for variant
IResource variant = RemoteImportExportUtil.getInstance().findExistingResourceVariant(path);
// if a variant does exist, return it
if (variant != null) {
return variant;
}
}
}
return null;
}
/**
* Returns the name of a container with a location that encompasses targetDirectory.
* Returns null if there is no conflict.
*
* @param targetDirectory the path of the directory to check.
* @return the conflicting container name or <code>null</code>
*/
protected String getConflictingContainerNameFor(String targetDirectory) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IPath testPath = new Path(targetDirectory);
if (root.getLocation().isPrefixOf(testPath)) return "workspace root"; //UniversalSystemPlugin.getString("IFSexport.rootName"); //$NON-NLS-1$
IProject[] projects = root.getProjects();
for (int i = 0; i < projects.length; i++) {
if (projects[i].getLocation().isPrefixOf(testPath)) return projects[i].getName();
}
return null;
}
/* (non-Javadoc)
* @see com.ibm.etools.systems.core.ui.wizards.ISystemWizardPage#setInputObject(java.lang.Object)
*/
public void setInputObject(Object inputObject) {
this.inputObject = inputObject;
}
/* (non-Javadoc)
* @see com.ibm.etools.systems.core.ui.wizards.ISystemWizardPage#getInputObject()
*/
public Object getInputObject() {
return inputObject;
}
/* (non-Javadoc)
* @see com.ibm.etools.systems.core.ui.wizards.ISystemWizardPage#performFinish()
*/
public boolean performFinish() {
return finish();
}
/* (non-Javadoc)
* @see com.ibm.etools.systems.core.ui.wizards.ISystemWizardPage#setHelp(java.lang.String)
*/
public void setHelp(String id) {
if (parentComposite != null) SystemWidgetHelpers.setHelp(parentComposite, helpId);
this.helpId = id;
}
/* (non-Javadoc)
* @see com.ibm.etools.systems.core.ui.wizards.ISystemWizardPage#getHelpContextId()
*/
public String getHelpContextId() {
return helpId;
}
/**
* ISystemMessageLine method. <br>
* Clears the currently displayed error message and redisplayes
* the message which was active before the error message was set.
*/
public void clearErrorMessage() {
if (msgLine != null)
msgLine.clearErrorMessage();
else
super.setErrorMessage(null);
}
/**
* ISystemMessageLine method. <br>
* Clears the currently displayed message.
*/
public void clearMessage() {
if (msgLine != null)
msgLine.clearMessage();
else
super.setMessage(null);
}
/**
* ISystemMessageLine method. <br>
* Get the currently displayed error text.
* @return The error message. If no error message is displayed <code>null</code> is returned.
*/
public SystemMessage getSystemErrorMessage() {
if (msgLine != null)
return msgLine.getSystemErrorMessage();
else
return null;
}
/**
* ISystemMessageLine method. <br>
* Display the given error message. A currently displayed message
* is saved and will be redisplayed when the error message is cleared.
*/
public void setErrorMessage(SystemMessage message) {
if (msgLine != null) {
if (message != null)
msgLine.setErrorMessage(message);
else
msgLine.clearErrorMessage();
} else // not configured yet
{
pendingErrorMessage = message;
super.setErrorMessage(message.getLevelOneText());
}
}
/**
* ISystemMessageLine method. <br>
* Convenience method to set an error message from an exception
*/
public void setErrorMessage(Throwable exc) {
if (msgLine != null)
msgLine.setErrorMessage(exc);
else {
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_UNEXPECTED);
msg.makeSubstitution(exc);
pendingErrorMessage = msg;
super.setErrorMessage(msg.getLevelOneText());
}
}
/**
* ISystemMessageLine method. <br>
* Display the given error message. A currently displayed message
* is saved and will be redisplayed when the error message is cleared.
*/
public void setErrorMessage(String message) {
if (msgLine != null) msgLine.setErrorMessage(message);
// super.setErrorMessage(message);
// if (msgLine != null)
// ((SystemDialogPageMessageLine)msgLine).internalSetErrorMessage(message);
}
/**
* ISystemMessageLine method. <br>
* If the message line currently displays an error,
* the message is stored and will be shown after a call to clearErrorMessage
*/
public void setMessage(SystemMessage message) {
if (msgLine != null)
msgLine.setMessage(message);
else // not configured yet
{
pendingMessage = message;
super.setMessage(message.getLevelOneText());
}
}
/**
* ISystemMessageLine method. <br>
* Set the non-error message text. If the message line currently displays an error,
* the message is stored and will be shown after a call to clearErrorMessage
*/
public void setMessage(String message) {
if (msgLine != null) msgLine.setMessage(message);
// super.setMessage(message);
// if (msgLine!=null)
// ((SystemDialogPageMessageLine)msgLine).internalSetMessage(message);
}
}

View file

@ -0,0 +1,104 @@
package org.eclipse.rse.files.importexport.files;
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.io.File;
import java.io.IOException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.services.files.RemoteFileException;
import org.eclipse.rse.services.files.RemoteFileSecurityException;
import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem;
// Similar to org.eclipse.ui.wizards.datatransfer.FileSystemExporter
/**
* Helper class for exporting resources to the file system.
*/
class RemoteExporter {
private Object as400 = null;
/**
* Create an instance of this class. Use this constructor if you wish to
* use an AS400 object */
public RemoteExporter(IHost s) {
super();
as400 = s;
}
/**
* Create an instance of this class.
*/
public RemoteExporter() {
super();
}
/**
* Creates the specified file system directory at <code>destinationPath</code>.
* This creates a new file system directory.
*/
public void createFolder(IPath destinationPath) {
// IFS: use IFSJaveFile object if necessary
if (as400 != null)
new UniFilePlus(Utilities.getIRemoteFile((IHost) as400, destinationPath.toString())).mkdir();
else
new File(destinationPath.toOSString()).mkdir();
}
/**
* Writes the passed resource to the specified location recursively
*/
public void write(IResource resource, IPath destinationPath) throws IOException, CoreException, RemoteFileSecurityException, RemoteFileException {
if (resource.getType() == IResource.FILE)
writeFile((IFile) resource, destinationPath);
else
writeChildren((IContainer) resource, destinationPath);
}
/**
* Exports the passed container's children
*/
protected void writeChildren(IContainer folder, IPath destinationPath) throws IOException, CoreException, RemoteFileSecurityException, RemoteFileException {
if (folder.isAccessible()) {
IResource[] children = folder.members();
for (int i = 0; i < children.length; i++) {
IResource child = children[i];
writeResource(child, destinationPath.append(child.getName()));
}
}
}
/**
* Writes the passed file resource to the specified destination on the remote
* file system
*/
protected void writeFile(IFile file, IPath destinationPath) throws IOException, CoreException, RemoteFileSecurityException, RemoteFileException {
IRemoteFileSubSystem rfss = RemoteFileUtility.getFileSubSystem((IHost) as400);
rfss.upload(file.getLocation().makeAbsolute().toOSString(), destinationPath.toString(), null);
}
/**
* Writes the passed resource to the specified location recursively
*/
protected void writeResource(IResource resource, IPath destinationPath) throws IOException, CoreException, RemoteFileSecurityException, RemoteFileException {
if (resource.getType() == IResource.FILE)
writeFile((IFile) resource, destinationPath);
else {
createFolder(destinationPath);
writeChildren((IContainer) resource, destinationPath);
}
}
}

View file

@ -0,0 +1,157 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IAction;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.files.importexport.RemoteImportExportProblemDialog;
import org.eclipse.rse.files.importexport.RemoteImportExportResources;
import org.eclipse.rse.services.clientserver.messages.SystemMessage;
import org.eclipse.rse.ui.ISystemMessages;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.ui.messages.SystemMessageDialog;
import org.eclipse.ui.PlatformUI;
/**
* This class is a remote file export action.
*/
public class RemoteFileExportActionDelegate extends RemoteFileImportExportActionDelegate {
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
IFile[] descriptions = getDescriptionFiles(getSelection());
MultiStatus mergedStatus;
int length = descriptions.length;
if (length < 1) {
return;
}
// create read multi status
String message;
if (length > 1) {
message = RemoteImportExportResources.IMPORT_EXPORT_ERROR_CREATE_FILES_FAILED;
} else {
message = RemoteImportExportResources.IMPORT_EXPORT_ERROR_CREATE_FILE_FAILED;
}
MultiStatus readStatus = new MultiStatus(RSEUIPlugin.getDefault().getSymbolicName(), 0, message, null);
RemoteFileExportData[] exportDatas = readExportDatas(descriptions, readStatus);
if (exportDatas.length > 0) {
IStatus status = export(exportDatas);
if (status == null) {
return;
}
if (readStatus.getSeverity() == IStatus.ERROR) {
message = readStatus.getMessage();
} else {
message = status.getMessage();
}
// create new status because we want another message - no API to set message
mergedStatus = new MultiStatus(RSEUIPlugin.getDefault().getSymbolicName(), status.getCode(), readStatus.getChildren(), message, null);
mergedStatus.merge(status);
} else {
mergedStatus = readStatus;
}
if (!mergedStatus.isOK()) {
RemoteImportExportProblemDialog.open(getShell(), RemoteImportExportResources.IMPORT_EXPORT_EXPORT_ACTION_DELEGATE_TITLE, null, mergedStatus);
}
}
private RemoteFileExportData[] readExportDatas(IFile[] descriptions, MultiStatus readStatus) {
List exportDataList = new ArrayList(descriptions.length);
for (int i = 0; i < descriptions.length; i++) {
RemoteFileExportData exportData = readExportData(descriptions[i], readStatus);
if (exportData != null) {
exportDataList.add(exportData);
}
}
return (RemoteFileExportData[]) exportDataList.toArray(new RemoteFileExportData[exportDataList.size()]);
}
/**
* Reads the file export data from a file.
*/
protected RemoteFileExportData readExportData(IFile description, MultiStatus readStatus) {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(Utilities.EXPORT_DESCRIPTION_EXTENSION));
RemoteFileExportData exportData = new RemoteFileExportData();
IRemoteFileExportDescriptionReader reader = null;
try {
reader = exportData.createExportDescriptionReader(description.getContents());
// read export data
reader.read(exportData);
// do not save settings again
exportData.setSaveSettings(false);
} catch (CoreException ex) {
String message = MessageFormat.format(RemoteImportExportResources.IMPORT_EXPORT_ERROR_DESCRIPTION_READ, new Object[] { description.getFullPath(), ex.getStatus().getMessage() });
addToStatus(readStatus, message, ex);
return null;
} finally {
if (reader != null) {
readStatus.addAll(reader.getStatus());
}
try {
if (reader != null) {
reader.close();
}
} catch (CoreException ex) {
String message = MessageFormat.format(RemoteImportExportResources.IMPORT_EXPORT_ERROR_DESCRIPTION_CLOSE, new Object[] { description.getFullPath() });
addToStatus(readStatus, message, ex);
}
}
return exportData;
}
private IStatus export(RemoteFileExportData[] exportDatas) {
IStatus status = null;
for (int i = 0; i < exportDatas.length; i++) {
RemoteFileExportOperation op = new RemoteFileExportOperation(exportDatas[i], new RemoteFileOverwriteQuery());
try {
PlatformUI.getWorkbench().getProgressService().run(true, true, op);
status = op.getStatus();
} catch (InvocationTargetException e) {
SystemBasePlugin.logError("Error occured trying to export", e); //$NON-NLS-1$
status = new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, "", e); //$NON-NLS-1$
} catch (InterruptedException e) {
SystemBasePlugin.logError("Error occured trying to export", e); //$NON-NLS-1$
status = new Status(IStatus.OK, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, "", e); //$NON-NLS-1$
}
if (!status.isOK()) {
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_FAILED);
msg.makeSubstitution(status);
SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg);
dlg.openWithDetails();
return null;
}
}
return null;
}
protected void addToStatus(MultiStatus multiStatus, String defaultMessage, CoreException ex) {
IStatus status = ex.getStatus();
String message = ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
status = new Status(status.getSeverity(), status.getPlugin(), status.getCode(), defaultMessage, ex);
}
multiStatus.add(status);
}
}

View file

@ -0,0 +1,173 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.rse.core.SystemBasePlugin;
/**
* Holds data of what to export.
*/
public class RemoteFileExportData {
private String destination;
private boolean overWriteExistingFiles;
private boolean createDirectoryStructure;
private boolean createSelectionOnly;
private boolean saveSettings;
private String descriptionFilePath;
// export elements
private List elements;
/**
* Constructor.
*/
public RemoteFileExportData() {
setDestination(null);
setOverWriteExistingFiles(false);
setCreateDirectoryStructure(false);
setCreateSelectionOnly(true);
setSaveSettings(false);
setDescriptionFilePath(null);
}
/**
* @return Returns the descriptionFilePath.
*/
public String getDescriptionFilePath() {
return descriptionFilePath;
}
/**
* Gets the description file as a workspace resource.
* @return a file representing the description file.
*/
public IFile getDescriptionFile() {
IPath path = new Path(getDescriptionFilePath());
if (path.isValidPath(path.toString()) && path.segmentCount() >= 2) {
return SystemBasePlugin.getWorkspace().getRoot().getFile(path);
} else {
return null;
}
}
/**
* @param descriptionFilePath The descriptionFilePath to set.
*/
public void setDescriptionFilePath(String descriptionFilePath) {
this.descriptionFilePath = descriptionFilePath;
}
/**
* @return Returns the destination.
*/
public String getDestination() {
return destination;
}
/**
* @param destination The destination to set.
*/
public void setDestination(String destination) {
this.destination = destination;
}
/**
* Returns the elements to be exported.
* @return the elements.
*/
public List getElements() {
return elements;
}
/**
* Sets the elements to export.
* @param elements the elements.
*/
public void setElements(List elements) {
this.elements = elements;
}
/**
* @return Returns the overWriteExistingFiles.
*/
public boolean isOverWriteExistingFiles() {
return overWriteExistingFiles;
}
/**
* @param overWriteExistingFiles The overWriteExistingFiles to set.
*/
public void setOverWriteExistingFiles(boolean overWriteExistingFiles) {
this.overWriteExistingFiles = overWriteExistingFiles;
}
/**
* @return Returns the saveSettings.
*/
public boolean isSaveSettings() {
return saveSettings;
}
/**
* @param saveSettings The saveSettings to set.
*/
public void setSaveSettings(boolean saveSettings) {
this.saveSettings = saveSettings;
}
/**
* @return Returns the createDirectoryStructure.
*/
public boolean isCreateDirectoryStructure() {
return createDirectoryStructure;
}
/**
* @param createDirectoryStructure The createDirectoryStructure to set.
*/
public void setCreateDirectoryStructure(boolean createDirectoryStructure) {
this.createDirectoryStructure = createDirectoryStructure;
}
/**
* @return Returns the createSelectionOnly.
*/
public boolean isCreateSelectionOnly() {
return createSelectionOnly;
}
/**
* @param createSelectionOnly The createSelectionOnly to set.
*/
public void setCreateSelectionOnly(boolean createSelectionOnly) {
this.createSelectionOnly = createSelectionOnly;
}
/**
* Creates and returns an export description writer.
*/
public IRemoteFileExportDescriptionWriter createExportDescriptionWriter(OutputStream outputStream) {
return new RemoteFileExportDescriptionWriter(outputStream);
}
/**
* Creates and returns an export description writer.
*/
public IRemoteFileExportDescriptionReader createExportDescriptionReader(InputStream inputStream) {
return new RemoteFileExportDescriptionReader(inputStream);
}
}

View file

@ -0,0 +1,202 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Remote file export description reader.
*/
public class RemoteFileExportDescriptionReader implements IRemoteFileExportDescriptionReader {
protected InputStream fInputStream;
/**
* Constructor.
*/
public RemoteFileExportDescriptionReader(InputStream inputStream) {
Assert.isNotNull(inputStream);
fInputStream = new BufferedInputStream(inputStream);
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileExportDescriptionReader#read(org.eclipse.rse.files.importexport.files.RemoteFileExportData)
*/
public void read(RemoteFileExportData exportData) throws CoreException {
try {
readXML(exportData);
} catch (IOException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
} catch (SAXException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
}
}
public RemoteFileExportData readXML(RemoteFileExportData exportData) throws IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder parser = null;
try {
parser = factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(ex.getLocalizedMessage());
}
Element xmlFileDesc = parser.parse(new InputSource(fInputStream)).getDocumentElement();
if (!xmlFileDesc.getNodeName().equals(Utilities.EXPORT_DESCRIPTION_EXTENSION)) {
throw new IOException();
}
NodeList topLevelElements = xmlFileDesc.getChildNodes();
for (int i = 0; i < topLevelElements.getLength(); i++) {
Node node = topLevelElements.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) node;
xmlReadDestinationLocation(exportData, element);
xmlReadOptions(exportData, element);
xmlReadSelectedElements(exportData, element);
}
return exportData;
}
private void xmlReadDestinationLocation(RemoteFileExportData exportData, Element element) {
if (element.getNodeName().equals("destination")) { //$NON-NLS-1$
exportData.setDestination(element.getAttribute("path")); //$NON-NLS-1$
}
}
private void xmlReadOptions(RemoteFileExportData exportData, Element element) throws IOException {
if (element.getNodeName().equals("options")) { //$NON-NLS-1$
exportData.setOverWriteExistingFiles(getBooleanAttribute(element, "overWriteExistingFiles")); //$NON-NLS-1$
exportData.setCreateDirectoryStructure(getBooleanAttribute(element, "createDirectoryStructure")); //$NON-NLS-1$
exportData.setCreateSelectionOnly(getBooleanAttribute(element, "createSelectedOnly")); //$NON-NLS-1$
exportData.setSaveSettings(getBooleanAttribute(element, "saveSettings")); //$NON-NLS-1$
exportData.setDescriptionFilePath(element.getAttribute("descriptionFilePath")); //$NON-NLS-1$
}
}
private void xmlReadSelectedElements(RemoteFileExportData exportData, Element element) throws IOException {
if (element.getNodeName().equals("selectedElements")) { //$NON-NLS-1$
NodeList selectedElements = element.getChildNodes();
List elementsToExport = new ArrayList(selectedElements.getLength());
for (int j = 0; j < selectedElements.getLength(); j++) {
Node selectedNode = selectedElements.item(j);
if (selectedNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element selectedElement = (Element) selectedNode;
if (selectedElement.getNodeName().equals("file")) { //$NON-NLS-1$
addFile(elementsToExport, selectedElement);
} else if (selectedElement.getNodeName().equals("folder")) { //$NON-NLS-1$
addFolder(elementsToExport, selectedElement);
} else if (selectedElement.getNodeName().equals("project")) { //$NON-NLS-1$
addProject(elementsToExport, selectedElement);
}
}
exportData.setElements(elementsToExport);
}
}
private void addFile(List selectedElements, Element element) throws IOException {
IPath path = getPath(element);
if (path != null) {
IFile file = SystemBasePlugin.getWorkspace().getRoot().getFile(path);
if (file != null) {
selectedElements.add(file);
}
}
}
private void addFolder(List selectedElements, Element element) throws IOException {
IPath path = getPath(element);
if (path != null) {
IFolder folder = SystemBasePlugin.getWorkspace().getRoot().getFolder(path);
if (folder != null) {
selectedElements.add(folder);
}
}
}
private void addProject(List selectedElements, Element element) throws IOException {
String name = element.getAttribute("name"); //$NON-NLS-1$
if (name.equals("")) { //$NON-NLS-1$
throw new IOException();
}
IProject project = SystemBasePlugin.getWorkspace().getRoot().getProject(name);
if (project != null) {
selectedElements.add(project);
}
}
private IPath getPath(Element element) throws IOException {
String pathString = element.getAttribute("path"); //$NON-NLS-1$
if (pathString.equals("")) { //$NON-NLS-1$
throw new IOException();
}
return new Path(element.getAttribute("path")); //$NON-NLS-1$
}
protected boolean getBooleanAttribute(Element element, String name) throws IOException {
String value = element.getAttribute(name);
if (value != null && value.equalsIgnoreCase("true")) { //$NON-NLS-1$
return true;
}
if (value != null && value.equalsIgnoreCase("false")) { //$NON-NLS-1$
return false;
}
throw new IOException();
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileExportDescriptionReader#close()
*/
public void close() throws CoreException {
if (fInputStream != null) {
try {
fInputStream.close();
} catch (IOException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
}
}
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileExportDescriptionReader#getStatus()
*/
public IStatus getStatus() {
return new Status(IStatus.OK, RSEUIPlugin.getDefault().getSymbolicName(), 0, "", null); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,169 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Remote file export description writer.
*/
public class RemoteFileExportDescriptionWriter implements IRemoteFileExportDescriptionWriter {
protected OutputStream fOutputStream;
/**
* Constructor.
*/
public RemoteFileExportDescriptionWriter(OutputStream outputStream) {
Assert.isNotNull(outputStream);
fOutputStream = new BufferedOutputStream(outputStream);
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileExportDescriptionWriter#write(org.eclipse.rse.files.importexport.files.RemoteFileExportData)
*/
public void write(RemoteFileExportData exportData) throws CoreException {
try {
writeXML(exportData);
} catch (IOException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
}
}
/**
* Writes a XML representation of file export data.
* @exception IOException if writing to the underlying stream fails.
*/
public void writeXML(RemoteFileExportData exportData) throws IOException {
Assert.isNotNull(exportData);
DocumentBuilder docBuilder = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
docBuilder = factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(ex.getLocalizedMessage());
}
Document document = docBuilder.newDocument();
// create the document
Element xmlFileDesc = document.createElement(Utilities.EXPORT_DESCRIPTION_EXTENSION);
document.appendChild(xmlFileDesc);
xmlWriteDestinationLocation(exportData, document, xmlFileDesc);
xmlWriteOptions(exportData, document, xmlFileDesc);
xmlWriteSelectedElements(exportData, document, xmlFileDesc);
try {
// write the document to the stream
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(fOutputStream);
transformer.transform(source, result);
} catch (TransformerException e) {
throw new IOException(e.getLocalizedMessage());
}
}
private void xmlWriteDestinationLocation(RemoteFileExportData exportData, Document document, Element xmlFileDesc) throws DOMException {
Element destination = document.createElement("destination"); //$NON-NLS-1$
xmlFileDesc.appendChild(destination);
destination.setAttribute("path", exportData.getDestination()); //$NON-NLS-1$
}
private void xmlWriteOptions(RemoteFileExportData exportData, Document document, Element xmlFileDesc) throws DOMException {
Element options = document.createElement("options"); //$NON-NLS-1$
xmlFileDesc.appendChild(options);
options.setAttribute("overWriteExistingFiles", "" + exportData.isOverWriteExistingFiles()); //$NON-NLS-1$ //$NON-NLS-2$
options.setAttribute("createDirectoryStructure", "" + exportData.isCreateDirectoryStructure()); //$NON-NLS-1$ //$NON-NLS-2$
options.setAttribute("createSelectedOnly", "" + exportData.isCreateSelectionOnly()); //$NON-NLS-1$ //$NON-NLS-2$
options.setAttribute("saveSettings", "" + exportData.isSaveSettings()); //$NON-NLS-1$ //$NON-NLS-2$
options.setAttribute("descriptionFilePath", "" + exportData.getDescriptionFilePath()); //$NON-NLS-1$ //$NON-NLS-2$
}
private void xmlWriteSelectedElements(RemoteFileExportData exportData, Document document, Element xmlFileDesc) throws DOMException {
Element selectedElements = document.createElement("selectedElements"); //$NON-NLS-1$
xmlFileDesc.appendChild(selectedElements);
List elements = exportData.getElements();
Iterator iter = elements.iterator();
while (iter.hasNext()) {
Object element = iter.next();
if (element instanceof IResource) {
add((IResource) element, selectedElements, document);
}
}
}
private void add(IResource resource, Element parent, Document document) {
Element element = null;
if (resource.getType() == IResource.PROJECT) {
element = document.createElement("project"); //$NON-NLS-1$
parent.appendChild(element);
element.setAttribute("name", resource.getName()); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
element = document.createElement("file"); //$NON-NLS-1$
} else if (resource.getType() == IResource.FOLDER) {
element = document.createElement("folder"); //$NON-NLS-1$
}
if (element != null) {
parent.appendChild(element);
element.setAttribute("path", resource.getFullPath().toString()); //$NON-NLS-1$
}
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileExportDescriptionWriter#close()
*/
public void close() throws CoreException {
if (fOutputStream != null) {
try {
fOutputStream.close();
} catch (IOException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
}
}
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileExportDescriptionWriter#getStatus()
*/
public IStatus getStatus() {
return new Status(IStatus.OK, RSEUIPlugin.getDefault().getSymbolicName(), 0, "", null); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,31 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.wizard.WizardDialog;
/**
* This class represents the action to bring up the remote file system export wizard
* and export the contents of a project or projects to a remote folder.
*/
public class RemoteFileExportFromProjectActionDelegate extends RemoteFileImportExportActionDelegate {
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
RemoteExportWizard wizard = new RemoteExportWizard();
wizard.init(getWorkbench(), getSelection());
WizardDialog dialog = new WizardDialog(getShell(), wizard);
dialog.create();
dialog.open();
}
}

View file

@ -0,0 +1,536 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.files.importexport.RemoteImportExportUtil;
import org.eclipse.rse.files.ui.resources.SystemIFileProperties;
import org.eclipse.rse.importexport.SystemImportExportResources;
import org.eclipse.rse.services.files.RemoteFileIOException;
import org.eclipse.rse.services.files.RemoteFileSecurityException;
import org.eclipse.rse.ui.ISystemMessages;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.IOverwriteQuery;
/**
* Operation for exporting the contents of a resource to the local file system.
*/
class RemoteFileExportOperation implements IRunnableWithProgress {
private IHost conn;
private IPath path;
private IProgressMonitor monitor;
private RemoteExporter exporter;
private List resourcesToExport;
private IOverwriteQuery overwriteCallback;
private IResource resource;
private List errorTable = new ArrayList(1);
private RemoteFileExportData exportData;
private boolean saveSettings;
private String descriptionFilePath;
// the constants for the overwrite 3 state
private static final int OVERWRITE_NOT_SET = 0;
private static final int OVERWRITE_NONE = 1;
private static final int OVERWRITE_ALL = 2;
private int overwriteState = OVERWRITE_NOT_SET;
private boolean createLeadupStructure = true;
private boolean createContainerDirectories = true;
/**
* Create an instance of this class. Use this constructor if you wish to
* export specific resources with a common parent resource (affects container
* directory creation).
*/
private RemoteFileExportOperation(IHost conn, IResource resource, List resources, String destinationPath, IOverwriteQuery overwriteImplementor) {
this.conn = conn;
this.resource = resource;
this.resourcesToExport = resources;
this.path = new Path(destinationPath);
this.overwriteCallback = overwriteImplementor;
this.exporter = new RemoteExporter(conn);
}
public RemoteFileExportOperation(RemoteFileExportData data, IOverwriteQuery overwriteImplementor) {
this(Utilities.parseForSystemConnection(data.getDestination()), null, data.getElements(), Utilities.parseForPath(data.getDestination()), overwriteImplementor);
this.exportData = data;
this.saveSettings = data.isSaveSettings();
this.descriptionFilePath = data.getDescriptionFilePath();
setCreateLeadupStructure(data.isCreateDirectoryStructure());
setOverwriteFiles(data.isOverWriteExistingFiles());
}
/**
* Add a new entry to the error table with the passed information
*/
protected void addError(String message, Throwable e) {
errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, message, e));
}
/**
* Answer the total number of file resources that exist at or below self in the
* resources hierarchy.
*
* @return int
* @param resource org.eclipse.core.resources.IResource
*/
protected int countChildrenOf(IResource resource) throws CoreException {
if (resource.getType() == IResource.FILE) return 1;
int count = 0;
if (resource.isAccessible()) {
IResource[] children = ((IContainer) resource).members();
for (int i = 0; i < children.length; i++)
count += countChildrenOf(children[i]);
}
return count;
}
/**
* Answer a boolean indicating the number of file resources that were
* specified for export
*
* @return int
*/
protected int countSelectedResources() throws CoreException {
int result = 0;
Iterator resources = resourcesToExport.iterator();
while (resources.hasNext())
result += countChildrenOf((IResource) resources.next());
return result;
}
/**
* Create the directories required for exporting the passed resource,
* based upon its container hierarchy
*
* @param resource org.eclipse.core.resources.IResource
*/
protected void createLeadupDirectoriesFor(IResource resource) {
IPath resourcePath = resource.getFullPath().removeLastSegments(1);
for (int i = 0; i < resourcePath.segmentCount(); i++) {
path = path.append(resourcePath.segment(i));
exporter.createFolder(path);
}
}
/**
* Recursively export the previously-specified resource
*/
protected void exportAllResources() throws InterruptedException {
if (resource.getType() == IResource.FILE)
exportFile((IFile) resource, path);
else {
try {
exportChildren(((IContainer) resource).members(), path);
} catch (CoreException e) {
// not safe to show a dialog
// should never happen because the file system export wizard ensures that the
// single resource chosen for export is both existent and accessible
errorTable.add(e);
}
}
}
/**
* Export all of the resources contained in the passed collection
*
* @param children java.util.Enumeration
* @param currentPath IPath
*/
protected void exportChildren(IResource[] children, IPath currentPath) throws InterruptedException {
for (int i = 0; i < children.length; i++) {
IResource child = children[i];
if (!child.isAccessible()) continue;
if (child.getType() == IResource.FILE)
exportFile((IFile) child, currentPath);
else {
IPath destination = currentPath.append(child.getName());
try {
exporter.createFolder(destination);
} catch (Exception e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_ERROR, new Object[] { destination, e.getLocalizedMessage() == null ? e.toString() : e.getMessage(), e })
.toString();
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, e));
}
try {
exportChildren(((IContainer) child).members(), destination);
} catch (CoreException e) {
// not safe to show a dialog
// should never happen because:
// i. this method is called recursively iterating over the result of #members,
// which only answers existing children
// ii. there is an #isAccessible check done before #members is invoked
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, e.getMessage(), e));
//errorTable.add(e.getStatus());
}
}
}
}
/**
* Export the passed file to the specified location
*
* @param file org.eclipse.core.resources.IFile
* @param location org.eclipse.core.runtime.IPath
*/
protected void exportFile(IFile file, IPath location) throws InterruptedException {
IPath fullPath = location.append(file.getName());
String destination = fullPath.toString();
// flag to indicate whether export is required
boolean exportRequired = false;
monitor.subTask(file.getFullPath().toString());
String properPathString = fullPath.toOSString();
File targetFile = null;
if (conn == null) {
targetFile = new File(properPathString);
} else {
try {
targetFile = new UniFilePlus(Utilities.getIRemoteFile(conn, fullPath.toString()));
} catch (NullPointerException e) {
// Assume that communication has failed.
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_ERROR,
new Object[] { fullPath, RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_IMPORT_EXPORT_UNABLE_TO_USE_CONNECTION).getLevelOneText(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, e));
throw e;
}
}
if (targetFile.exists()) {
exportRequired = isExportRequired(file, destination);
// if export is not required, no need to do anything
if (!exportRequired) {
return;
}
if (!targetFile.canWrite()) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_NOT_WRITABLE, targetFile.getAbsolutePath()).toString();
errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, msg, null));
monitor.worked(1);
return;
}
if (overwriteState == OVERWRITE_NONE) {
return;
} else if (overwriteState != OVERWRITE_ALL) {
String overwriteAnswer = overwriteCallback.queryOverwrite(properPathString);
if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) {
throw new InterruptedException();
} else if (overwriteAnswer.equals(IOverwriteQuery.NO)) {
monitor.worked(1);
return;
} else if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) {
monitor.worked(1);
overwriteState = OVERWRITE_NONE;
return;
} else if (overwriteAnswer.equals(IOverwriteQuery.ALL)) {
overwriteState = OVERWRITE_ALL;
}
}
} else if (!targetFile.exists()) {
// need to do an export if target file does not exist, even if the local
// file has not changed. This is for the scenario where a file may have been
// exported, and the server copy was later deleted. The next export should put
// the local copy back on the server, even if the local file was not changed.
exportRequired = true;
}
try {
exporter.write(file, fullPath);
// if there are no exceptions, we should be here and the export should have completed fine
// so we update the modification time at the time of export
SystemIFileProperties props = new SystemIFileProperties(file);
long modTime = file.getModificationStamp();
props.setModificationStampAtExport(conn.getHostName(), destination, modTime);
} catch (IOException e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_ERROR, new Object[] { fullPath, e.getLocalizedMessage(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, msg, e));
} catch (CoreException e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_ERROR, new Object[] { fullPath, e.getLocalizedMessage(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, msg, e));
} catch (RemoteFileIOException e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_ERROR, new Object[] { fullPath, e.getLocalizedMessage(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, e));
} catch (RemoteFileSecurityException e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_ERROR, new Object[] { fullPath, e.getLocalizedMessage(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, e));
} catch (Exception e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_ERROR, new Object[] { fullPath, e.getLocalizedMessage(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, msg, e));
}
monitor.worked(1);
ModalContext.checkCanceled(monitor);
}
protected boolean isExportRequired(IFile file, String destinationPath) {
if (conn != null) {
// get the host name of the connection
String hostName = conn.getHostName();
SystemIFileProperties props = new SystemIFileProperties(file);
// check if we have a modification time stored for the hostname/destination path combination
boolean hasModTime = props.hasModificationStampAtExport(hostName, destinationPath);
// if not, that means we are exporting for the first time
if (!hasModTime) {
return true;
}
// otherwise, check if the modification time stored is different to the modification time
// of the file
else {
long modTime = props.getModificationStampAtExport(hostName, destinationPath);
long currentModTime = file.getModificationStamp();
// if the modification timestamps are different, then the file has changed
// since the last export to the destination, so we need export it again
if (modTime != currentModTime) {
return true;
}
// otherwise, do not export
else {
return false;
}
}
}
return true;
}
/**
* Export the resources contained in the previously-defined
* resourcesToExport collection
*/
protected void exportSpecifiedResources() throws InterruptedException {
Iterator resources = resourcesToExport.iterator();
IPath initPath = (IPath) path.clone();
while (resources.hasNext()) {
IResource currentResource = (IResource) resources.next();
if (!currentResource.isAccessible()) continue;
path = initPath;
if (resource == null) {
// No root resource specified and creation of containment directories
// is required. Create containers from depth 2 onwards (ie.- project's
// child inclusive) for each resource being exported.
if (createLeadupStructure) createLeadupDirectoriesFor(currentResource);
} else {
// Root resource specified. Must create containment directories
// from this point onwards for each resource being exported
IPath containersToCreate = currentResource.getFullPath().removeFirstSegments(resource.getFullPath().segmentCount()).removeLastSegments(1);
for (int i = 0; i < containersToCreate.segmentCount(); i++) {
path = path.append(containersToCreate.segment(i));
exporter.createFolder(path);
}
}
if (currentResource.getType() == IResource.FILE)
exportFile((IFile) currentResource, path);
else {
if (createContainerDirectories) {
path = path.append(currentResource.getName());
exporter.createFolder(path);
}
try {
exportChildren(((IContainer) currentResource).members(), path);
} catch (CoreException e) {
// should never happen because #isAccessible is called before #members is invoked,
// which implicitly does an existence check
errorTable.add(e.getStatus());
}
}
}
}
/**
* Returns the status of the export operation.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status
*/
public IStatus getStatus() {
IStatus[] errors = new IStatus[errorTable.size()];
errorTable.toArray(errors);
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_EXPORT_PROBLEMS).getLevelOneText();
return new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, errors, msg, null);
}
/**
* Answer a boolean indicating whether the passed child is a descendent
* of one or more members of the passed resources collection
*
* @return boolean
* @param resources java.util.List
* @param child org.eclipse.core.resources.IResource
*/
protected boolean isDescendent(List resources, IResource child) {
if (child.getType() == IResource.PROJECT) return false;
IResource parent = child.getParent();
if (resources.contains(parent)) return true;
return isDescendent(resources, parent);
}
/**
* Export the resources that were previously specified for export
* (or if a single resource was specified then export it recursively)
*/
public void run(IProgressMonitor monitor) throws InterruptedException {
this.monitor = monitor;
if (resource != null) {
if (createLeadupStructure) createLeadupDirectoriesFor(resource);
if (createContainerDirectories && resource.getType() != IResource.FILE) { // ensure it's a container
path = path.append(resource.getName());
exporter.createFolder(path);
}
}
try {
int totalWork = IProgressMonitor.UNKNOWN;
try {
if (resourcesToExport == null)
totalWork = countChildrenOf(resource);
else
totalWork = countSelectedResources();
} catch (CoreException e) {
// Should not happen
errorTable.add(e.getStatus());
}
String taskMsg = SystemImportExportResources.RESID_FILEEXPORT_EXPORTING;
monitor.beginTask(taskMsg, totalWork);
if (resourcesToExport == null) {
exportAllResources();
} else {
exportSpecifiedResources();
}
if (saveSettings) {
try {
saveDescription();
} catch (CoreException e) {
SystemBasePlugin.logError("Error occured trying to save description " + descriptionFilePath, e); //$NON-NLS-1$
errorTable.add(e.getStatus());
} catch (IOException e) {
SystemBasePlugin.logError("Error occured trying to save description " + descriptionFilePath, e); //$NON-NLS-1$
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, e.getLocalizedMessage(), e));
}
}
} finally {
monitor.done();
}
}
/**
* Saves a description file for the export.
* @throws CoreException if an unexpected exception occurs.
* @throws IOException if an I/O error occurs.
*/
protected void saveDescription() throws CoreException, IOException {
ByteArrayOutputStream objectStreamOutput = new ByteArrayOutputStream();
IRemoteFileExportDescriptionWriter writer = exportData.createExportDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput = null;
try {
writer.write(exportData);
fileInput = new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile = exportData.getDescriptionFile();
// check if resource exists
if (descriptionFile.isAccessible()) {
descriptionFile.setContents(fileInput, true, true, null);
}
// if resource does not exist
else {
// now have to check if a variant of this file exists (i.e. whether a file exists
// that has the same path with a different case. For case insensitive file systems
// such as Windows, this is needed since we can't simply create a file with a different
// case. Note that isAccessible() above does not check for file paths with different case,
// so we have to check it explicitly).
IResource variant = RemoteImportExportUtil.getInstance().findExistingResourceVariant(descriptionFile.getFullPath());
// if a variant was not found, create the new file
if (variant == null) {
// check if a variant of the parent exists
// we need to do this because at this point we know that the file path does not
// exist, and neither does its variant. However, it is possible that the parent path
// has a variant, in which case calling create on the description file with
// the path as it is given will fail. We need to get the variant path of the parent,
// append the name of the file to the variant path, and create a file with that path.
// get parent
IResource parent = descriptionFile.getParent();
if (parent != null) {
// get parent path
IResource parentVariant = RemoteImportExportUtil.getInstance().findExistingResourceVariant(parent.getFullPath());
// no parent variant (i.e. in a case sensitive file system)
if (parentVariant == null) {
descriptionFile.create(fileInput, true, null);
}
// parent variant found (might be same as original parent path)
else {
IPath newPath = parentVariant.getFullPath().append(descriptionFile.getName());
IFile newDescriptionFile = SystemBasePlugin.getWorkspace().getRoot().getFile(newPath);
newDescriptionFile.create(fileInput, true, null);
}
}
}
// otherwise, simply set the contents of the variant file
else {
if (variant instanceof IFile) {
((IFile) variant).setContents(fileInput, true, true, null);
}
}
}
} finally {
if (fileInput != null) {
fileInput.close();
}
if (writer != null) {
writer.close();
}
}
}
/**
* Set this boolean indicating whether a directory should be created for
* Folder resources that are explicitly passed for export
*
* @param value boolean
*/
public void setCreateContainerDirectories(boolean value) {
createContainerDirectories = value;
}
/**
* Set this boolean indicating whether each exported resource's complete path should
* include containment hierarchies as dictated by its parents
*
* @param value boolean
*/
public void setCreateLeadupStructure(boolean value) {
createLeadupStructure = value;
}
/**
* Set this boolean indicating whether exported resources should automatically
* overwrite existing files when a conflict occurs
*
* @param value boolean
*/
public void setOverwriteFiles(boolean value) {
if (value) {
overwriteState = OVERWRITE_ALL;
}
}
}

View file

@ -0,0 +1,157 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IAction;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.files.importexport.RemoteImportExportProblemDialog;
import org.eclipse.rse.files.importexport.RemoteImportExportResources;
import org.eclipse.rse.services.clientserver.messages.SystemMessage;
import org.eclipse.rse.ui.ISystemMessages;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.ui.messages.SystemMessageDialog;
import org.eclipse.ui.PlatformUI;
/**
* This class is a remote file import action.
*/
public class RemoteFileImportActionDelegate extends RemoteFileImportExportActionDelegate {
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
IFile[] descriptions = getDescriptionFiles(getSelection());
MultiStatus mergedStatus;
int length = descriptions.length;
if (length < 1) {
return;
}
// create read multi status
String message;
if (length > 1) {
message = RemoteImportExportResources.IMPORT_EXPORT_ERROR_CREATE_FILES_FAILED;
} else {
message = RemoteImportExportResources.IMPORT_EXPORT_ERROR_CREATE_FILE_FAILED;
}
MultiStatus readStatus = new MultiStatus(RSEUIPlugin.getDefault().getSymbolicName(), 0, message, null);
RemoteFileImportData[] importDatas = readImportDatas(descriptions, readStatus);
if (importDatas.length > 0) {
IStatus status = importFiles(importDatas);
if (status == null) {
return;
}
if (readStatus.getSeverity() == IStatus.ERROR) {
message = readStatus.getMessage();
} else {
message = status.getMessage();
}
// create new status because we want another message - no API to set message
mergedStatus = new MultiStatus(RSEUIPlugin.getDefault().getSymbolicName(), status.getCode(), readStatus.getChildren(), message, null);
mergedStatus.merge(status);
} else {
mergedStatus = readStatus;
}
if (!mergedStatus.isOK()) {
RemoteImportExportProblemDialog.open(getShell(), RemoteImportExportResources.IMPORT_EXPORT_IMPORT_ACTION_DELEGATE_TITLE, null, mergedStatus);
}
}
private RemoteFileImportData[] readImportDatas(IFile[] descriptions, MultiStatus readStatus) {
List importDataList = new ArrayList(descriptions.length);
for (int i = 0; i < descriptions.length; i++) {
RemoteFileImportData importData = readImportData(descriptions[i], readStatus);
if (importData != null) {
importDataList.add(importData);
}
}
return (RemoteFileImportData[]) importDataList.toArray(new RemoteFileImportData[importDataList.size()]);
}
/**
* Reads the file import data from a file.
*/
protected RemoteFileImportData readImportData(IFile description, MultiStatus readStatus) {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(Utilities.IMPORT_DESCRIPTION_EXTENSION));
RemoteFileImportData importData = new RemoteFileImportData();
IRemoteFileImportDescriptionReader reader = null;
try {
reader = importData.createImportDescriptionReader(description.getContents());
// read export data
reader.read(importData);
// do not save settings again
importData.setSaveSettings(false);
} catch (CoreException ex) {
String message = MessageFormat.format(RemoteImportExportResources.IMPORT_EXPORT_ERROR_DESCRIPTION_READ, new Object[] { description.getFullPath(), ex.getStatus().getMessage() });
addToStatus(readStatus, message, ex);
return null;
} finally {
if (reader != null) {
readStatus.addAll(reader.getStatus());
}
try {
if (reader != null) {
reader.close();
}
} catch (CoreException ex) {
String message = MessageFormat.format(RemoteImportExportResources.IMPORT_EXPORT_ERROR_DESCRIPTION_CLOSE, new Object[] { description.getFullPath() });
addToStatus(readStatus, message, ex);
}
}
return importData;
}
private IStatus importFiles(RemoteFileImportData[] importDatas) {
IStatus status = null;
for (int i = 0; i < importDatas.length; i++) {
RemoteFileImportOperation op = new RemoteFileImportOperation(importDatas[i], FileSystemStructureProvider.INSTANCE, new RemoteFileOverwriteQuery());
try {
PlatformUI.getWorkbench().getProgressService().run(true, true, op);
status = op.getStatus();
} catch (InvocationTargetException e) {
SystemBasePlugin.logError("Error occured trying to import", e); //$NON-NLS-1$
status = new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, "", e); //$NON-NLS-1$
} catch (InterruptedException e) {
SystemBasePlugin.logError("Error occured trying to import", e); //$NON-NLS-1$
status = new Status(IStatus.OK, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, "", e); //$NON-NLS-1$
}
if (!status.isOK()) {
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_IMPORT_FAILED);
msg.makeSubstitution(status);
SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg);
dlg.openWithDetails();
return null;
}
}
return null;
}
protected void addToStatus(MultiStatus multiStatus, String defaultMessage, CoreException ex) {
IStatus status = ex.getStatus();
String message = ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
status = new Status(status.getSeverity(), status.getPlugin(), status.getCode(), defaultMessage, ex);
}
multiStatus.add(status);
}
}

View file

@ -0,0 +1,218 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.rse.core.SystemBasePlugin;
/**
* Holds data of what to import.
*/
public class RemoteFileImportData {
private IPath containerPath;
private Object source;
private boolean overWriteExistingFiles;
private boolean createDirectoryStructure;
private boolean createSelectionOnly;
private boolean saveSettings;
private String descriptionFilePath;
// import elements
private HashMap map;
private List elements;
/**
* Constructor.
*/
public RemoteFileImportData() {
setContainerPath(null);
setSource(null);
setOverWriteExistingFiles(false);
setCreateDirectoryStructure(false);
setCreateSelectionOnly(true);
setSaveSettings(false);
setDescriptionFilePath(null);
}
/**
* @return Returns the descriptionFilePath.
*/
public String getDescriptionFilePath() {
return descriptionFilePath;
}
/**
* Gets the description file as a workspace resource.
* @return a file representing the description file.
*/
public IFile getDescriptionFile() {
IPath path = new Path(getDescriptionFilePath());
if (path.isValidPath(path.toString()) && path.segmentCount() >= 2) {
return SystemBasePlugin.getWorkspace().getRoot().getFile(path);
} else {
return null;
}
}
/**
* @param descriptionFilePath The descriptionFilePath to set.
*/
public void setDescriptionFilePath(String descriptionFilePath) {
this.descriptionFilePath = descriptionFilePath;
}
/**
* @return returns container path.
*/
public IPath getContainerPath() {
return containerPath;
}
/**
* @param containerPath the container path.
*/
public void setContainerPath(IPath containerPath) {
this.containerPath = containerPath;
}
/**
* Gets the source.
* @return the source from which to import.
*/
public Object getSource() {
return source;
}
/**
* Sets the source.
* @param source the source from which to import.
*/
public void setSource(Object source) {
this.source = source;
}
/**
* Returns the elements to be imported.
* @return the elements.
*/
public List getElements() {
return elements;
}
/**
* Sets the elements to imported.
* @param elements the elements.
*/
public void setElements(List elements) {
this.elements = elements;
}
/**
* Add to the list of files to import.
* @param object the file object.
*/
public void addToList(UniFilePlus object) {
if (map == null) {
map = new HashMap();
}
// add to map
map.put(object.getAbsolutePath(), object);
}
/**
* Does the file exist.
* @param object the file object.
* @return <code>true</code> of the
*/
public boolean doesExist(UniFilePlus object) {
if (map.get(object.getAbsolutePath()) == null) {
return false;
} else {
return true;
}
}
/**
* @return Returns the overWriteExistingFiles.
*/
public boolean isOverWriteExistingFiles() {
return overWriteExistingFiles;
}
/**
* @param overWriteExistingFiles The overWriteExistingFiles to set.
*/
public void setOverWriteExistingFiles(boolean overWriteExistingFiles) {
this.overWriteExistingFiles = overWriteExistingFiles;
}
/**
* @return Returns the saveSettings.
*/
public boolean isSaveSettings() {
return saveSettings;
}
/**
* @param saveSettings The saveSettings to set.
*/
public void setSaveSettings(boolean saveSettings) {
this.saveSettings = saveSettings;
}
/**
* @return Returns the createDirectoryStructure.
*/
public boolean isCreateDirectoryStructure() {
return createDirectoryStructure;
}
/**
* @param createDirectoryStructure The createDirectoryStructure to set.
*/
public void setCreateDirectoryStructure(boolean createDirectoryStructure) {
this.createDirectoryStructure = createDirectoryStructure;
}
/**
* @return Returns the createSelectionOnly.
*/
public boolean isCreateSelectionOnly() {
return createSelectionOnly;
}
/**
* @param createSelectionOnly The createSelectionOnly to set.
*/
public void setCreateSelectionOnly(boolean createSelectionOnly) {
this.createSelectionOnly = createSelectionOnly;
}
/**
* Creates and returns an import description writer.
*/
public IRemoteFileImportDescriptionWriter createImportDescriptionWriter(OutputStream outputStream) {
return new RemoteFileImportDescriptionWriter(outputStream);
}
/**
* Creates and returns an import description writer.
*/
public IRemoteFileImportDescriptionReader createImportDescriptionReader(InputStream inputStream) {
return new RemoteFileImportDescriptionReader(inputStream);
}
}

View file

@ -0,0 +1,192 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.services.clientserver.messages.SystemMessageException;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Remote file import description reader.
*/
public class RemoteFileImportDescriptionReader implements IRemoteFileImportDescriptionReader {
protected InputStream fInputStream;
protected IRemoteFileSubSystem subsystem;
/**
* Constructor.
*/
public RemoteFileImportDescriptionReader(InputStream inputStream) {
Assert.isNotNull(inputStream);
fInputStream = new BufferedInputStream(inputStream);
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileImportDescriptionReader#read(org.eclipse.rse.files.importexport.files.RemoteFileImportData)
*/
public void read(RemoteFileImportData importData) throws CoreException {
try {
readXML(importData);
} catch (IOException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
} catch (SAXException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
}
}
public RemoteFileImportData readXML(RemoteFileImportData importData) throws IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder parser = null;
try {
parser = factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(ex.getLocalizedMessage());
}
Element xmlFileDesc = parser.parse(new InputSource(fInputStream)).getDocumentElement();
if (!xmlFileDesc.getNodeName().equals(Utilities.IMPORT_DESCRIPTION_EXTENSION)) {
throw new IOException();
}
NodeList topLevelElements = xmlFileDesc.getChildNodes();
for (int i = 0; i < topLevelElements.getLength(); i++) {
Node node = topLevelElements.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE) continue;
Element element = (Element) node;
xmlReadDestinationLocation(importData, element);
xmlReadOptions(importData, element);
xmlReadSourceLocation(importData, element);
xmlReadSelectedElements(importData, element);
}
return importData;
}
private void xmlReadDestinationLocation(RemoteFileImportData importData, Element element) {
if (element.getNodeName().equals("destination")) { //$NON-NLS-1$
String destinationPath = element.getAttribute("path"); //$NON-NLS-1$
importData.setContainerPath(new Path(destinationPath));
}
}
private void xmlReadOptions(RemoteFileImportData importData, Element element) throws IOException {
if (element.getNodeName().equals("options")) { //$NON-NLS-1$
importData.setOverWriteExistingFiles(getBooleanAttribute(element, "overWriteExistingFiles")); //$NON-NLS-1$
importData.setCreateDirectoryStructure(getBooleanAttribute(element, "createDirectoryStructure")); //$NON-NLS-1$
importData.setCreateSelectionOnly(getBooleanAttribute(element, "createSelectedOnly")); //$NON-NLS-1$
importData.setSaveSettings(getBooleanAttribute(element, "saveSettings")); //$NON-NLS-1$
importData.setDescriptionFilePath(element.getAttribute("descriptionFilePath")); //$NON-NLS-1$
}
}
private void xmlReadSourceLocation(RemoteFileImportData importData, Element element) {
if (element.getNodeName().equals("source")) { //$NON-NLS-1$
String sourceCanonicalPath = element.getAttribute("path"); //$NON-NLS-1$
IRemoteFile remoteFile = Utilities.parseForIRemoteFile(sourceCanonicalPath);
UniFilePlus file = new UniFilePlus(remoteFile);
importData.setSource(file);
subsystem = remoteFile.getParentRemoteFileSubSystem();
}
}
private void xmlReadSelectedElements(RemoteFileImportData importData, Element element) throws IOException {
if (element.getNodeName().equals("selectedElements")) { //$NON-NLS-1$
NodeList selectedElements = element.getChildNodes();
List elementsToImport = new ArrayList(selectedElements.getLength());
for (int j = 0; j < selectedElements.getLength(); j++) {
Node selectedNode = selectedElements.item(j);
if (selectedNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element selectedElement = (Element) selectedNode;
if (selectedElement.getNodeName().equals("file")) { //$NON-NLS-1$
addResource(importData, elementsToImport, selectedElement);
} else if (selectedElement.getNodeName().equals("folder")) { //$NON-NLS-1$
addResource(importData, elementsToImport, selectedElement);
}
}
importData.setElements(elementsToImport);
}
}
private void addResource(RemoteFileImportData importData, List selectedElements, Element element) throws IOException {
String path = element.getAttribute("path"); //$NON-NLS-1$
if (path != null && subsystem != null) {
IRemoteFile remoteFile = null;
try {
remoteFile = subsystem.getRemoteFileObject(path);
if (remoteFile != null && remoteFile.exists()) {
UniFilePlus file = new UniFilePlus(remoteFile);
selectedElements.add(file);
// add to list of import data
importData.addToList(file);
}
} catch (SystemMessageException e) {
SystemBasePlugin.logError("Error occured trying to retrieve file " + path, e); //$NON-NLS-1$
}
}
}
protected boolean getBooleanAttribute(Element element, String name) throws IOException {
String value = element.getAttribute(name);
if (value != null && value.equalsIgnoreCase("true")) { //$NON-NLS-1$
return true;
}
if (value != null && value.equalsIgnoreCase("false")) { //$NON-NLS-1$
return false;
}
throw new IOException();
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileImportDescriptionReader#close()
*/
public void close() throws CoreException {
if (fInputStream != null) {
try {
fInputStream.close();
subsystem = null;
} catch (IOException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
}
}
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileImportDescriptionReader#getStatus()
*/
public IStatus getStatus() {
return new Status(IStatus.OK, RSEUIPlugin.getDefault().getSymbolicName(), 0, "", null); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,171 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Remote file import description writer.
*/
public class RemoteFileImportDescriptionWriter implements IRemoteFileImportDescriptionWriter {
protected OutputStream fOutputStream;
/**
* Constructor.
*/
public RemoteFileImportDescriptionWriter(OutputStream outputStream) {
Assert.isNotNull(outputStream);
fOutputStream = new BufferedOutputStream(outputStream);
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileImportDescriptionWriter#write(org.eclipse.rse.files.importexport.files.RemoteFileImportData)
*/
public void write(RemoteFileImportData importData) throws CoreException {
try {
writeXML(importData);
} catch (IOException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
}
}
/**
* Writes a XML representation of file import data.
* @exception IOException if writing to the underlying stream fails.
*/
public void writeXML(RemoteFileImportData importData) throws IOException {
Assert.isNotNull(importData);
DocumentBuilder docBuilder = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
docBuilder = factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(ex.getLocalizedMessage());
}
Document document = docBuilder.newDocument();
// create the document
Element xmlFileDesc = document.createElement(Utilities.IMPORT_DESCRIPTION_EXTENSION);
document.appendChild(xmlFileDesc);
xmlWriteDestinationLocation(importData, document, xmlFileDesc);
xmlWriteOptions(importData, document, xmlFileDesc);
xmlWriteSourceLocation(importData, document, xmlFileDesc);
xmlWriteSelectedElements(importData, document, xmlFileDesc);
try {
// write the document to the stream
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(fOutputStream);
transformer.transform(source, result);
} catch (TransformerException e) {
throw new IOException(e.getLocalizedMessage());
}
}
private void xmlWriteDestinationLocation(RemoteFileImportData importData, Document document, Element xmlFileDesc) throws DOMException {
Element destination = document.createElement("destination"); //$NON-NLS-1$
xmlFileDesc.appendChild(destination);
destination.setAttribute("path", importData.getContainerPath().toString()); //$NON-NLS-1$
}
private void xmlWriteOptions(RemoteFileImportData importData, Document document, Element xmlFileDesc) throws DOMException {
Element options = document.createElement("options"); //$NON-NLS-1$
xmlFileDesc.appendChild(options);
options.setAttribute("overWriteExistingFiles", "" + importData.isOverWriteExistingFiles()); //$NON-NLS-1$ //$NON-NLS-2$
options.setAttribute("createDirectoryStructure", "" + importData.isCreateDirectoryStructure()); //$NON-NLS-1$ //$NON-NLS-2$
options.setAttribute("createSelectedOnly", "" + importData.isCreateSelectionOnly()); //$NON-NLS-1$ //$NON-NLS-2$
options.setAttribute("saveSettings", "" + importData.isSaveSettings()); //$NON-NLS-1$ //$NON-NLS-2$
options.setAttribute("descriptionFilePath", "" + importData.getDescriptionFilePath()); //$NON-NLS-1$ //$NON-NLS-2$
}
private void xmlWriteSourceLocation(RemoteFileImportData importData, Document document, Element xmlFileDesc) throws DOMException {
Element source = document.createElement("source"); //$NON-NLS-1$
xmlFileDesc.appendChild(source);
UniFilePlus sourceResource = (UniFilePlus) (importData.getSource());
// save path along with profile and connection name
source.setAttribute("path", sourceResource.getCanonicalPath()); //$NON-NLS-1$
}
private void xmlWriteSelectedElements(RemoteFileImportData exportData, Document document, Element xmlFileDesc) throws DOMException {
Element selectedElements = document.createElement("selectedElements"); //$NON-NLS-1$
xmlFileDesc.appendChild(selectedElements);
List elements = exportData.getElements();
Iterator iter = elements.iterator();
while (iter.hasNext()) {
Object element = iter.next();
if (element instanceof UniFilePlus) {
add((UniFilePlus) element, selectedElements, document);
}
}
}
private void add(UniFilePlus resource, Element parent, Document document) {
Element element = null;
if (resource.isFile()) {
element = document.createElement("file"); //$NON-NLS-1$
} else if (resource.isDirectory()) {
element = document.createElement("folder"); //$NON-NLS-1$
}
if (element != null) {
parent.appendChild(element);
element.setAttribute("path", resource.getAbsolutePath()); //$NON-NLS-1$
}
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileImportDescriptionWriter#close()
*/
public void close() throws CoreException {
if (fOutputStream != null) {
try {
fOutputStream.close();
} catch (IOException ex) {
String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, message, ex));
}
}
}
/**
* @see org.eclipse.rse.files.importexport.files.IRemoteFileImportDescriptionWriter#getStatus()
*/
public IStatus getStatus() {
return new Status(IStatus.OK, RSEUIPlugin.getDefault().getSymbolicName(), 0, "", null); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,119 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.util.Iterator;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
/**
* This class is the super class of file import/export action delegate.
*/
public abstract class RemoteFileImportExportActionDelegate implements IActionDelegate {
protected IStructuredSelection fSelection;
/**
* Sets the selection. The selection is only set if given a structured selection, otherwise it is set to an
* empty structured selection.
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
if (selection instanceof IStructuredSelection) {
fSelection = (IStructuredSelection) selection;
} else {
fSelection = StructuredSelection.EMPTY;
}
}
/**
* Returns the remote file in the selection.
* Use this method if this action allows only a single remote file selection.
* @return the single remote file.
*/
protected IRemoteFile getRemoteFile(IStructuredSelection selection) {
return (IRemoteFile) selection.getFirstElement();
}
/**
* Returns the remote files in the selection.
* Use this method if this action allows multiple remote file selection.
* @return an array of remote files.
*/
protected IRemoteFile[] getRemoteFiles(IStructuredSelection selection) {
IRemoteFile[] files = new IRemoteFile[selection.size()];
Iterator iter = selection.iterator();
int i = 0;
while (iter.hasNext()) {
files[i++] = (IRemoteFile) iter.next();
}
return files;
}
/**
* Returns the description file for the first description file in
* the selection. Use this method if this action allows only
* a single file selection.
* @return the single description file.
*/
protected IFile getDescriptionFile(IStructuredSelection selection) {
return (IFile) selection.getFirstElement();
}
/**
* Returns a description file for each description file in
* the selection. Use this method if this action allows multiple
* selection.
* @return an array of description files.
*/
protected IFile[] getDescriptionFiles(IStructuredSelection selection) {
IFile[] files = new IFile[selection.size()];
Iterator iter = selection.iterator();
int i = 0;
while (iter.hasNext()) {
files[i++] = (IFile) iter.next();
}
return files;
}
/**
* Returns the workbench.
* @return the workbench.
*/
protected IWorkbench getWorkbench() {
return PlatformUI.getWorkbench();
}
/**
* Returns the active shell.
* @return the active shell.
*/
protected Shell getShell() {
return Display.getDefault().getActiveShell();
}
/**
* Returns the selection.
* @return the selection.
*/
protected IStructuredSelection getSelection() {
return fSelection;
}
}

View file

@ -0,0 +1,639 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.files.importexport.RemoteImportExportUtil;
import org.eclipse.rse.importexport.SystemImportExportResources;
import org.eclipse.rse.services.files.RemoteFileIOException;
import org.eclipse.rse.services.files.RemoteFileSecurityException;
import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem;
import org.eclipse.rse.ui.ISystemMessages;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.ContainerGenerator;
import org.eclipse.ui.dialogs.IOverwriteQuery;
// Similar to org.eclipse.ui.wizards.datatransfer.ImportOperation
/**
* An operation which does the actual work of copying objects from the local file
* system into the workspace.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class RemoteFileImportOperation extends WorkspaceModifyOperation {
private static final int POLICY_DEFAULT = 0;
private static final int POLICY_SKIP_CHILDREN = 1;
private static final int POLICY_FORCE_OVERWRITE = 2;
private Object source;
private IPath destinationPath;
private IContainer destinationContainer;
private List selectedFiles;
private IImportStructureProvider provider;
private IProgressMonitor monitor;
protected IOverwriteQuery overwriteCallback;
private List errorTable = new ArrayList();
private boolean createContainerStructure = true;
private RemoteFileImportData importData;
private boolean saveSettings;
private String descriptionFilePath;
//The constants for the overwrite 3 state
private static final int OVERWRITE_NOT_SET = 0;
private static final int OVERWRITE_NONE = 1;
private static final int OVERWRITE_ALL = 2;
private int overwriteState = OVERWRITE_NOT_SET;
/**
* Creates a new operation that recursively imports the entire contents of the
* specified root file system object.
* <p>
* The <code>source</code> parameter represents the root file system object to
* import. All contents of this object are imported. Valid types for this parameter
* are determined by the supplied <code>IImportStructureProvider</code>.
* </p>
* <p>
* The <code>provider</code> parameter allows this operation to deal with the
* source object in an abstract way. This operation calls methods on the provider
* and the provider in turn calls specific methods on the source object.
* </p>
* <p>
* The default import behavior is to recreate the complete container structure
* for the contents of the root file system object in their destination.
* If <code>setCreateContainerStructure</code> is set to false then the container
* structure created is relative to the root file system object.
* </p>
*
* @param containerPath the full path of the destination container within the
* workspace
* @param source the root file system object to import
* @param provider the file system structure provider to use
* @param overwriteImplementor the overwrite strategy to use
*/
public RemoteFileImportOperation(IPath containerPath, Object source, IImportStructureProvider provider, IOverwriteQuery overwriteImplementor) {
super();
this.destinationPath = containerPath;
this.source = source;
this.provider = provider;
overwriteCallback = overwriteImplementor;
}
/**
* Creates a new operation that imports specific file system objects.
* In this usage context, the specified source file system object is used by the
* operation solely to determine the destination container structure of the file system
* objects being imported.
* <p>
* The <code>source</code> parameter represents the root file system object to
* import. Valid types for this parameter are determined by the supplied
* <code>IImportStructureProvider</code>. The contents of the source which
* are to be imported are specified in the <code>filesToImport</code>
* parameter.
* </p>
* <p>
* The <code>provider</code> parameter allows this operation to deal with the
* source object in an abstract way. This operation calls methods on the provider
* and the provider in turn calls specific methods on the source object.
* </p>
* <p>
* The <code>filesToImport</code> parameter specifies what contents of the root
* file system object are to be imported.
* </p>
* <p>
* The default import behavior is to recreate the complete container structure
* for the file system objects in their destination. If <code>setCreateContainerStructure</code>
* is set to <code>false</code>, then the container structure created for each of
* the file system objects is relative to the supplied root file system object.
* </p>
*
* @param containerPath the full path of the destination container within the
* workspace
* @param source the root file system object to import from
* @param provider the file system structure provider to use
* @param overwriteImplementor the overwrite strategy to use
* @param filesToImport the list of file system objects to be imported
* (element type: <code>Object</code>)
*/
public RemoteFileImportOperation(IPath containerPath, Object source, IImportStructureProvider provider, IOverwriteQuery overwriteImplementor, List filesToImport) {
this(containerPath, source, provider, overwriteImplementor);
setFilesToImport(filesToImport);
}
public RemoteFileImportOperation(RemoteFileImportData data, IImportStructureProvider provider, IOverwriteQuery overwriteImplementor) {
this(data.getContainerPath(), data.getSource(), provider, overwriteImplementor);
setFilesToImport(data.getElements());
setOverwriteResources(data.isOverWriteExistingFiles());
setCreateContainerStructure(data.isCreateDirectoryStructure());
this.importData = data;
this.saveSettings = data.isSaveSettings();
this.descriptionFilePath = data.getDescriptionFilePath();
}
/**
* Creates a new operation that imports specific file system objects.
* <p>
* The <code>provider</code> parameter allows this operation to deal with the
* source object in an abstract way. This operation calls methods on the provider
* and the provider in turn calls specific methods on the source object.
* </p>
* <p>
* The <code>filesToImport</code> parameter specifies what file system objects
* are to be imported.
* </p>
* <p>
* The default import behavior is to recreate the complete container structure
* for the file system objects in their destination. If <code>setCreateContainerStructure</code>
* is set to <code>false</code>, then no container structure is created for each of
* the file system objects.
* </p>
*
* @param containerPath the full path of the destination container within the
* workspace
* @param provider the file system structure provider to use
* @param overwriteImplementor the overwrite strategy to use
* @param filesToImport the list of file system objects to be imported
* (element type: <code>Object</code>)
*/
public RemoteFileImportOperation(IPath containerPath, IImportStructureProvider provider, IOverwriteQuery overwriteImplementor, List filesToImport) {
this(containerPath, null, provider, overwriteImplementor);
setFilesToImport(filesToImport);
}
/**
* Creates the folders that appear in the specified resource path.
* These folders are created relative to the destination container.
*
* @param path the relative path of the resource
* @return the container resource coresponding to the given path
* @exception CoreException if this method failed
*/
IContainer createContainersFor(IPath path) throws CoreException {
IContainer currentFolder = destinationContainer;
int segmentCount = path.segmentCount();
//No containers to create
if (segmentCount == 0) return currentFolder;
//Needs to be handles differently at the root
if (currentFolder.getType() == IResource.ROOT) return createFromRoot(path);
for (int i = 0; i < segmentCount; i++) {
currentFolder = currentFolder.getFolder(new Path(path.segment(i)));
if (!currentFolder.exists()) ((IFolder) currentFolder).create(false, true, null);
}
return currentFolder;
}
/**
* Creates the folders that appear in the specified resource path
* assuming that the destinationContainer begins at the root. Do not create projects.
*
* @param path the relative path of the resource
* @return the container resource coresponding to the given path
* @exception CoreException if this method failed
*/
private IContainer createFromRoot(IPath path) throws CoreException {
int segmentCount = path.segmentCount();
//Assume the project exists
IContainer currentFolder = ((IWorkspaceRoot) destinationContainer).getProject(path.segment(0));
for (int i = 1; i < segmentCount; i++) {
currentFolder = currentFolder.getFolder(new Path(path.segment(i)));
if (!currentFolder.exists()) ((IFolder) currentFolder).create(false, true, null);
}
return currentFolder;
}
/**
* Deletes the given resource. If the resource fails to be deleted, adds a
* status object to the list to be returned by <code>getResult</code>.
*
* @param resource the resource
*/
void deleteResource(IResource resource) {
try {
resource.delete(IResource.KEEP_HISTORY, null);
} catch (CoreException e) {
errorTable.add(e.getStatus());
}
}
/**
* Attempts to ensure that the given resource does not already exist in the
* workspace. The resource will be deleted if required, perhaps after asking
* the user's permission.
*
* @param targetResource the resource that should not exist
* @param policy determines how the resource is imported
* @return <code>true</code> if the resource does not exist, and
* <code>false</code> if it does exist
*/
boolean ensureTargetDoesNotExist(IResource targetResource, int policy) {
if (targetResource.exists()) {
//If force overwrite is on don't bother
if (policy != POLICY_FORCE_OVERWRITE) {
if (this.overwriteState == OVERWRITE_NOT_SET && !queryOverwrite(targetResource.getFullPath())) return false;
if (this.overwriteState == OVERWRITE_NONE) return false;
}
deleteResource(targetResource);
}
return true;
}
/* (non-Javadoc)
* Method declared on WorkbenchModifyOperation.
* Imports the specified file system objects from the file system.
*/
protected void execute(IProgressMonitor progressMonitor) {
monitor = progressMonitor;
try {
if (selectedFiles == null) {
//Set the amount to 1000 as we have no idea of how long this will take
String taskMsg = SystemImportExportResources.RESID_FILEIMPORT_IMPORTING;
monitor.beginTask(taskMsg, 1000);
ContainerGenerator generator = new ContainerGenerator(destinationPath);
monitor.worked(50);
destinationContainer = generator.generateContainer(new SubProgressMonitor(monitor, 50));
importRecursivelyFrom(source, POLICY_DEFAULT);
//Be sure it finishes
monitor.worked(90);
} else {
// Choose twice the selected files size to take folders into account
int creationCount = selectedFiles.size();
String taskMsg = SystemImportExportResources.RESID_FILEIMPORT_IMPORTING;
monitor.beginTask(taskMsg, creationCount + 100);
ContainerGenerator generator = new ContainerGenerator(destinationPath);
monitor.worked(50);
destinationContainer = generator.generateContainer(new SubProgressMonitor(monitor, 50));
importFileSystemObjects(selectedFiles);
}
if (saveSettings) {
try {
saveDescription();
} catch (CoreException e) {
SystemBasePlugin.logError("Error occured trying to save description " + descriptionFilePath, e); //$NON-NLS-1$
errorTable.add(e.getStatus());
} catch (IOException e) {
SystemBasePlugin.logError("Error occured trying to save description " + descriptionFilePath, e); //$NON-NLS-1$
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getSymbolicName(), 0, e.getLocalizedMessage(), e));
}
}
} catch (CoreException e) {
errorTable.add(e.getStatus());
} finally {
monitor.done();
}
}
/**
* Saves a description file for the export.
* @throws CoreException if an unexpected exception occurs.
* @throws IOException if an I/O error occurs.
*/
protected void saveDescription() throws CoreException, IOException {
ByteArrayOutputStream objectStreamOutput = new ByteArrayOutputStream();
IRemoteFileImportDescriptionWriter writer = importData.createImportDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput = null;
try {
writer.write(importData);
fileInput = new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile = importData.getDescriptionFile();
// check if resource exists
if (descriptionFile.isAccessible()) {
descriptionFile.setContents(fileInput, true, true, null);
}
// if resource does not exist
else {
// now have to check if a variant of this file exists (i.e. whether a file exists
// that has the same path with a different case. For case insensitive file systems
// such as Windows, this is needed since we can't simply create a file with a different
// case. Note that isAccessible() above does not check for file paths with different case,
// so we have to check it explicitly).
IResource variant = RemoteImportExportUtil.getInstance().findExistingResourceVariant(descriptionFile.getFullPath());
// if a variant was not found, create the new file
if (variant == null) {
// check if a variant of the parent exists
// we need to do this because at this point we know that the file path does not
// exist, and neither does its variant. However, it is possible that the parent path
// has a variant, in which case calling create on the description file with
// the path as it is given will fail. We need to get the variant path of the parent,
// append the name of the file to the variant path, and create a file with that path.
// get parent
IResource parent = descriptionFile.getParent();
if (parent != null) {
// get parent path
IResource parentVariant = RemoteImportExportUtil.getInstance().findExistingResourceVariant(parent.getFullPath());
// no parent variant (i.e. in a case sensitive file system)
if (parentVariant == null) {
descriptionFile.create(fileInput, true, null);
}
// parent variant found (might be same as original parent path)
else {
IPath newPath = parentVariant.getFullPath().append(descriptionFile.getName());
IFile newDescriptionFile = SystemBasePlugin.getWorkspace().getRoot().getFile(newPath);
newDescriptionFile.create(fileInput, true, null);
}
}
}
// otherwise, simply set the contents of the variant file
else {
if (variant instanceof IFile) {
((IFile) variant).setContents(fileInput, true, true, null);
}
}
}
} finally {
if (fileInput != null) {
fileInput.close();
}
if (writer != null) {
writer.close();
}
}
}
/**
* Returns the container resource that the passed file system object should be
* imported into.
*
* @param fileSystemObject the file system object being imported
* @return the container resource that the passed file system object should be
* imported into
* @exception CoreException if this method failed
*/
IContainer getDestinationContainerFor(Object fileSystemObject) throws CoreException {
IPath pathname = new Path(provider.getFullPath(fileSystemObject));
if (createContainerStructure)
return createContainersFor(pathname.removeLastSegments(1));
else {
if (source == fileSystemObject) return null;
IPath sourcePath = new Path(provider.getFullPath(source));
IPath destContainerPath = pathname.removeLastSegments(1);
IPath relativePath = destContainerPath.removeFirstSegments(sourcePath.segmentCount()).setDevice(null);
return createContainersFor(relativePath);
}
}
/**
* Returns the status of the import operation.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status
*/
public IStatus getStatus() {
IStatus[] errors = new IStatus[errorTable.size()];
errorTable.toArray(errors);
// IFS:
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_IMPORT_PROBLEMS).getLevelOneText();
return new MultiStatus(RSEUIPlugin.getDefault().getBundle().getSymbolicName(), IStatus.OK, errors, msg, null);
}
/**
* Imports the specified file system object into the workspace.
* If the import fails, adds a status object to the list to be returned by
* <code>getResult</code>.
*
* @param fileObject the file system object to be imported
* @param policy determines how the file object is imported
*/
void importFile(Object fileObject, int policy) {
IContainer containerResource;
try {
containerResource = getDestinationContainerFor(fileObject);
} catch (CoreException e) {
IStatus coreStatus = e.getStatus();
String newMessage = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_IMPORT_ERROR, new Object[] { fileObject, coreStatus.getMessage(), e }).toString();
IStatus status = new Status(coreStatus.getSeverity(), coreStatus.getPlugin(), coreStatus.getCode(), newMessage, null);
errorTable.add(status);
return;
}
String fileObjectPath = provider.getFullPath(fileObject);
monitor.subTask(fileObjectPath);
IFile targetResource = containerResource.getFile(new Path(provider.getLabel(fileObject)));
monitor.worked(1);
// ensure that the source and target are not the same
IPath targetPath = targetResource.getLocation();
// Use Files for comparison to avoid platform specific case issues
if (targetPath != null && (targetPath.toFile().equals(new File(fileObjectPath)))) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_IMPORT_SELF, fileObjectPath).toString();
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, null));
return;
}
if (!ensureTargetDoesNotExist(targetResource, policy)) {
// Do not add an error status because the user
// has explicitely said no overwrite. Do not
// update the monitor as it was done in queryOverwrite.
return;
}
try {
IRemoteFileSubSystem rfss = RemoteFileUtility.getFileSubSystem(((UniFilePlus) fileObject).remoteFile.getSystemConnection());
// 030820: added the following kludge to circumvent problem in
// artemis. (artemis 3 will fix this)
// TODO remove for 6.0
String encoding = System.getProperty("file.encoding"); //$NON-NLS-1$
if (encoding.startsWith("CP")) //$NON-NLS-1$
{
encoding = "Cp" + encoding.substring(2); //$NON-NLS-1$
}
rfss.download(((UniFilePlus) fileObject).remoteFile, targetResource, encoding, null);
try {
// refresh workspace with just added resource
targetResource.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
} catch (CoreException e) {
errorTable.add(e.getStatus());
}
} catch (RemoteFileIOException e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_IMPORT_ERROR, new Object[] { fileObjectPath, e.getRemoteException().getLocalizedMessage(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, e));
return;
} catch (RemoteFileSecurityException e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_IMPORT_ERROR, new Object[] { fileObjectPath, e.getRemoteException().getLocalizedMessage(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, e));
return;
} catch (Exception e) {
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_IMPORT_ERROR, new Object[] { fileObjectPath, e.getMessage() == null ? e.toString() : e.getMessage(), e }).toString();
errorTable.add(new Status(IStatus.ERROR, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, e));
return;
}
}
/**
* Imports the specified file system objects into the workspace.
* If the import fails, adds a status object to the list to be returned by
* <code>getStatus</code>.
*
* @param filesToImport the list of file system objects to import
* (element type: <code>Object</code>)
* @exception OperationCanceledException if canceled
*/
void importFileSystemObjects(List filesToImport) {
Iterator filesEnum = filesToImport.iterator();
while (filesEnum.hasNext()) {
Object fileSystemObject = filesEnum.next();
if (source == null) {
// We just import what we are given into the destination
IPath sourcePath = new Path(provider.getFullPath(fileSystemObject)).removeLastSegments(1);
if (provider.isFolder(fileSystemObject) && sourcePath.isEmpty()) {
// If we don't have a parent then we have selected the
// file systems root. Roots can't copied (at least not
// under windows).
String msg = RSEUIPlugin.getPluginMessage(ISystemMessages.FILEMSG_COPY_ROOT).toString();
errorTable.add(new Status(IStatus.INFO, RSEUIPlugin.getDefault().getBundle().getSymbolicName(), 0, msg, null));
continue;
}
source = sourcePath.toFile();
}
importRecursivelyFrom(fileSystemObject, POLICY_DEFAULT);
}
}
/**
* Imports the specified file system container object into the workspace.
* If the import fails, adds a status object to the list to be returned by
* <code>getResult</code>.
*
* @param fileObject the file system container object to be imported
* @param policy determines how the folder object and children are imported
* @return the policy to use to import the folder's children
*/
int importFolder(Object folderObject, int policy) {
IContainer containerResource;
try {
containerResource = getDestinationContainerFor(folderObject);
} catch (CoreException e) {
errorTable.add(e.getStatus());
return policy;
}
if (containerResource == null) return policy;
monitor.subTask(provider.getFullPath(folderObject));
IWorkspace workspace = destinationContainer.getWorkspace();
IPath containerPath = containerResource.getFullPath();
IPath resourcePath = containerPath.append(provider.getLabel(folderObject));
// Do not attempt the import if the resource path is unchanged. This may happen
// when importing from a zip file.
if (resourcePath.equals(containerPath)) return policy;
if (workspace.getRoot().exists(resourcePath)) {
if (policy != POLICY_FORCE_OVERWRITE) {
if (this.overwriteState == OVERWRITE_NONE || !queryOverwrite(resourcePath)) // Do not add an error status because the user
// has explicitely said no overwrite. Do not
// update the monitor as it was done in queryOverwrite.
return POLICY_SKIP_CHILDREN;
}
return POLICY_FORCE_OVERWRITE;
}
try {
workspace.getRoot().getFolder(resourcePath).create(false, true, null);
} catch (CoreException e) {
errorTable.add(e.getStatus());
}
return policy;
}
/**
* Imports the specified file system object recursively into the workspace.
* If the import fails, adds a status object to the list to be returned by
* <code>getStatus</code>.
*
* @param fileSystemObject the file system object to be imported
* @param policy determines how the file system object and children are imported
* @exception OperationCanceledException if canceled
*/
void importRecursivelyFrom(Object fileSystemObject, int policy) {
if (monitor.isCanceled()) throw new OperationCanceledException();
if (!provider.isFolder(fileSystemObject)) {
importFile(fileSystemObject, policy);
return;
}
int childPolicy = importFolder(fileSystemObject, policy);
if (childPolicy != POLICY_SKIP_CHILDREN) {
Iterator children = provider.getChildren(fileSystemObject).iterator();
while (children.hasNext())
importRecursivelyFrom(children.next(), childPolicy);
}
}
/**
* Queries the user whether the resource with the specified path should be
* overwritten by a file system object that is being imported.
*
* @param path the workspace path of the resource that needs to be overwritten
* @return <code>true</code> to overwrite, <code>false</code> to not overwrite
* @exception OperationCanceledException if canceled
*/
boolean queryOverwrite(IPath resourcePath) throws OperationCanceledException {
String overwriteAnswer = overwriteCallback.queryOverwrite(resourcePath.makeRelative().toString());
if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) //throw new OperationCanceledException(UniversalSystemPlugin.getString("customs.emptyString"));
throw new OperationCanceledException(""); //$NON-NLS-1$
if (overwriteAnswer.equals(IOverwriteQuery.NO)) {
return false;
}
if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) {
this.overwriteState = OVERWRITE_NONE;
return false;
}
if (overwriteAnswer.equals(IOverwriteQuery.ALL)) this.overwriteState = OVERWRITE_ALL;
return true;
}
/**
* Sets whether the containment structures that are implied from the full paths
* of file system objects being imported should be duplicated in the workbench.
*
* @param value <code>true</code> if containers should be created, and
* <code>false</code> otherwise
*/
public void setCreateContainerStructure(boolean value) {
createContainerStructure = value;
}
/**
* Sets the file system objects to import.
*
* @param filesToImport the list of file system objects to be imported
* (element type: <code>Object</code>)
*/
public void setFilesToImport(List filesToImport) {
this.selectedFiles = filesToImport;
}
/**
* Sets whether imported file system objects should automatically overwrite
* existing workbench resources when a conflict occurs.
*
* @param value <code>true</code> to automatically overwrite, and
* <code>false</code> otherwise
*/
public void setOverwriteResources(boolean value) {
if (value) this.overwriteState = OVERWRITE_ALL;
}
}

View file

@ -0,0 +1,31 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.wizard.WizardDialog;
/**
* This class represents the action to bring up the remote file system import wizard
* and import the contents of a remote folder to a project.
*/
public class RemoteFileImportToProjectActionDelegate extends RemoteFileImportExportActionDelegate {
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
RemoteImportWizard wizard = new RemoteImportWizard();
wizard.init(getWorkbench(), getSelection());
WizardDialog dialog = new WizardDialog(getShell(), wizard);
dialog.create();
dialog.open();
}
}

View file

@ -0,0 +1,82 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.IOException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.swt.widgets.Shell;
import org.xml.sax.SAXException;
/**
* Opens the remote file system export wizard.
*/
public class RemoteFileOpenExportWizardActionDelegate extends RemoteFileImportExportActionDelegate {
/**
* Opens the remote file system export wizard.
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
Shell parent = getShell();
RemoteFileExportData exportData = null;
IFile file = getDescriptionFile(getSelection());
if (file == null) {
SystemBasePlugin.logError("No description file found"); //$NON-NLS-1$
return;
}
try {
exportData = readRemoteFileExportData(file);
} catch (CoreException e) {
SystemBasePlugin.logError("Error occured trying to read description file" + file.getFullPath(), e); //$NON-NLS-1$
return;
} catch (IOException e) {
SystemBasePlugin.logError("Error occured trying to read description file" + file.getFullPath(), e); //$NON-NLS-1$
return;
} catch (SAXException e) {
SystemBasePlugin.logError("Error occured trying to read description file" + file.getFullPath(), e); //$NON-NLS-1$
return;
}
if (exportData == null) {
SystemBasePlugin.logError("No export data"); //$NON-NLS-1$
return;
}
RemoteExportWizard wizard = new RemoteExportWizard();
wizard.init(getWorkbench(), exportData);
WizardDialog dialog = new WizardDialog(parent, wizard);
dialog.create();
dialog.open();
}
/**
* Reads the remote file export data from a file.
*/
private RemoteFileExportData readRemoteFileExportData(IFile description) throws CoreException, IOException, SAXException {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(Utilities.EXPORT_DESCRIPTION_EXTENSION));
RemoteFileExportData exportData = new RemoteFileExportData();
IRemoteFileExportDescriptionReader reader = null;
try {
reader = exportData.createExportDescriptionReader(description.getContents());
reader.read(exportData);
} finally {
if (reader != null) {
reader.close();
}
}
return exportData;
}
}

View file

@ -0,0 +1,82 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.io.IOException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.swt.widgets.Shell;
import org.xml.sax.SAXException;
/**
* Opens the remote file system export wizard.
*/
public class RemoteFileOpenImportWizardActionDelegate extends RemoteFileImportExportActionDelegate {
/**
* Opens the remote file system export wizard.
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
Shell parent = getShell();
RemoteFileImportData importData = null;
IFile file = getDescriptionFile(getSelection());
if (file == null) {
SystemBasePlugin.logError("No description file found"); //$NON-NLS-1$
return;
}
try {
importData = readRemoteFileImportData(file);
} catch (CoreException e) {
SystemBasePlugin.logError("Error occured trying to read description file" + file.getFullPath(), e); //$NON-NLS-1$
return;
} catch (IOException e) {
SystemBasePlugin.logError("Error occured trying to read description file" + file.getFullPath(), e); //$NON-NLS-1$
return;
} catch (SAXException e) {
SystemBasePlugin.logError("Error occured trying to read description file" + file.getFullPath(), e); //$NON-NLS-1$
return;
}
if (importData == null) {
SystemBasePlugin.logError("No export data"); //$NON-NLS-1$
return;
}
RemoteImportWizard wizard = new RemoteImportWizard();
wizard.init(getWorkbench(), importData);
WizardDialog dialog = new WizardDialog(parent, wizard);
dialog.create();
dialog.open();
}
/**
* Reads the remote file export data from a file.
*/
private RemoteFileImportData readRemoteFileImportData(IFile description) throws CoreException, IOException, SAXException {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(Utilities.IMPORT_DESCRIPTION_EXTENSION));
RemoteFileImportData importData = new RemoteFileImportData();
IRemoteFileImportDescriptionReader reader = null;
try {
reader = importData.createImportDescriptionReader(description.getContents());
reader.read(importData);
} finally {
if (reader != null) {
reader.close();
}
}
return importData;
}
}

View file

@ -0,0 +1,94 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import java.text.MessageFormat;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.files.importexport.RemoteImportExportResources;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.IOverwriteQuery;
/**
* This class is used to query whether the user wants to overwrite a file, overwrite all files, not overwrite a file,
* not overwrite any files, or cancel.
*/
public class RemoteFileOverwriteQuery implements IOverwriteQuery {
/**
* This runnable shows the overwrite query dialog and stores the result.
*/
private class RemoteFileOverwriteQueryRunnable implements Runnable {
private String pathString;
private String queryResponse;
/**
* Constructor.
* @param pathString the path.
*/
private RemoteFileOverwriteQueryRunnable(String pathString) {
this.pathString = pathString;
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
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) {
//TODO internal class used
messageString = MessageFormat.format(RemoteImportExportResources.WizardDataTransfer_existsQuestion, new String[] { pathString });
} else {
// TODO internal class used
messageString = MessageFormat.format(RemoteImportExportResources.WizardDataTransfer_overwriteNameAndPathQuestion, new String[] { path.lastSegment(),
path.removeLastSegments(1).toOSString() });
}
Shell shell = SystemBasePlugin.getActiveWorkbenchShell();
// TODO internal class used
MessageDialog dialog = new MessageDialog(shell, RemoteImportExportResources.Question, 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 };
// open the dialog
dialog.open();
if (dialog.getReturnCode() < 0) {
queryResponse = IOverwriteQuery.CANCEL;
} else {
queryResponse = response[dialog.getReturnCode()];
}
}
private String getQueryRresponse() {
return queryResponse;
}
}
/**
* Constructor.
*/
public RemoteFileOverwriteQuery() {
super();
}
/**
* @see org.eclipse.ui.dialogs.IOverwriteQuery#queryOverwrite(java.lang.String)
*/
public String queryOverwrite(String pathString) {
RemoteFileOverwriteQueryRunnable runnable = new RemoteFileOverwriteQueryRunnable(pathString);
Display.getDefault().syncExec(runnable);
return runnable.getQueryRresponse();
}
}

View file

@ -0,0 +1,119 @@
package org.eclipse.rse.files.importexport.files;
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.rse.importexport.SystemImportExportResources;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.ui.wizards.AbstractSystemWizard;
import org.eclipse.ui.IImportWizard;
import org.eclipse.ui.IWorkbench;
// Similar to org.eclipse.ui.wizards.datatransfer.FileSystemImportWizard
// Changes marked with "IFS:" comments. Also see use of RemoteImportExportPlugin
/**
* Standard workbench wizard for importing resources from the local file system
* into the workspace.
* <p>
* This class may be instantiated and used without further configuration;
* this class is not intended to be subclassed.
* </p>
* <p>
* Example:
* <pre>
* IWizard wizard = new RemoteImportWizard();
* wizard.init(workbench, selection);
* WizardDialog dialog = new WizardDialog(shell, wizard);
* dialog.open();
* </pre>
* During the call to <code>open</code>, the wizard dialog is presented to the
* user. When the user hits Finish, the user-selected files are imported
* into the workspace, the dialog closes, and the call to <code>open</code>
* returns.
* </p>
*/
public class RemoteImportWizard extends AbstractSystemWizard implements IImportWizard {
private IWorkbench workbench;
private IStructuredSelection selection;
private RemoteImportWizardPage1 mainPage;
private RemoteFileImportData importData;
private boolean initializeFromExportData;
/**
* Creates a wizard for importing resources into the workspace from
* the file system.
*/
public RemoteImportWizard() {
IDialogSettings workbenchSettings = RSEUIPlugin.getDefault().getDialogSettings();
IDialogSettings section = workbenchSettings.getSection("RemoteImportWizard"); //$NON-NLS-1$
if (section == null) section = workbenchSettings.addNewSection("RemoteImportWizard"); //$NON-NLS-1$
setDialogSettings(section);
}
/* (non-Javadoc)
* Method declared on IWizard.
*/
public void addPages() {
mainPage = new RemoteImportWizardPage1(workbench, selection);
addPage(mainPage);
}
/**
* Returns the image descriptor with the given relative path.
*/
private ImageDescriptor getImageDescriptor(String relativePath) {
String iconPath = "icons/full/"; //$NON-NLS-1$
return RSEUIPlugin.getDefault().getPluginImage(iconPath + relativePath);
}
/* (non-Javadoc)
* Method declared on IWorkbenchWizard.
*/
public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
this.workbench = workbench;
selection = currentSelection;
setWindowTitle(SystemImportExportResources.RESID_FILEIMPORT_TITLE);
setDefaultPageImageDescriptor(getImageDescriptor("wizban/import_wiz.gif")); //$NON-NLS-1$
setNeedsProgressMonitor(true);
}
public void init(IWorkbench workbench, RemoteFileImportData importData) {
this.workbench = workbench;
this.selection = new StructuredSelection(importData.getElements().toArray());
this.importData = importData;
setInitializeFromImportData(true);
setWindowTitle(SystemImportExportResources.RESID_FILEIMPORT_TITLE);
setDefaultPageImageDescriptor(getImageDescriptor("wizban/import_wiz.gif")); //$NON-NLS-1$
setNeedsProgressMonitor(true);
}
protected void setInitializeFromImportData(boolean init) {
this.initializeFromExportData = init;
}
public boolean getInitializeFromImportData() {
return initializeFromExportData;
}
public RemoteFileImportData getImportData() {
return importData;
}
/* (non-Javadoc)
* Method declared on IWizard.
*/
public boolean performFinish() {
return mainPage.finish();
}
}

View file

@ -0,0 +1,89 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/**
* TreeExpandDropListener provides automatic expansion for Trees during drag and drop
* operations.
* <p>
* If the pointer hovers for a time over an item in the Tree that has not yet been
* expanded, the item is expanded automatically. This behaviour is consistent with
* that of popular GUI systems.
* </p><p>
* To use it send addDropListener(new TreeExpandDropListener(tree)) to the DropTarget
* object attached to the Tree.
* </p>
*/
public class TreeExpandDropListener extends DropTargetAdapter {
public static final long DEFAULT_EXPAND_DELAY = 1000; // millis
private long hoverThreshhold = DEFAULT_EXPAND_DELAY;
private long hoverBegin = 0;
private TreeItem hoverItem = null;
private Tree tree;
/**
* Constructs a Tree expanding Drop Listener
*
* @param tree the Tree that the DropTarget is attached to
*/
public TreeExpandDropListener(final Tree tree) {
this.tree = tree;
}
/**
* Handles dragEnter events.
* This is an implementation detail.
*/
public void dragEnter(DropTargetEvent event) {
hoverItem = null;
}
/**
* Handles dragOver events.
* This is an implementation detail.
*/
public void dragOver(DropTargetEvent event) {
Point point = tree.toControl(new Point(event.x, event.y));
// Get the item directly under the point
TreeItem item = tree.getItem(point);
if (item != hoverItem) {
// We just started hovering, remember this item
if ((item != null) && (!item.getExpanded())) {
hoverBegin = System.currentTimeMillis();
hoverItem = item;
} else {
hoverItem = null;
}
} else if (hoverItem != null) {
// We've been hovering for a while, expand if our timer elapsed
long hoverCurrent = System.currentTimeMillis();
if (hoverCurrent - hoverBegin >= hoverThreshhold) {
// Fake as if the user expanded the item manually
Event hoverEvent = new Event();
hoverEvent.x = event.x;
hoverEvent.y = event.y;
hoverEvent.item = hoverItem;
hoverEvent.time = (int) hoverCurrent;
hoverItem.setExpanded(true);
hoverItem = null;
tree.notifyListeners(SWT.Expand, hoverEvent);
}
}
}
}

View file

@ -0,0 +1,145 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/**
* TreeScrollDropListener provides automatic scrolling for Trees during drag and drop
* operations.
* <p>
* If the pointer drags over an item in the Tree near its upper or
* lower edges, the Tree will scroll so as to make previous or successive items visible
* onscreen. This behaviour is consistent with that of popular GUI systems.
* </p><p>
* To use it send addDropListener(new TreeScrollDropListener(tree)) to the DropTarget
* object attached to the Tree.
* </p>
*/
public class TreeScrollDropListener extends DropTargetAdapter {
private Tree tree;
/**
* Constructs a Tree scrolling Drop Listener
*
* @param tree the Tree that the DropTarget is attached to
*/
public TreeScrollDropListener(final Tree tree) {
this.tree = tree;
}
/**
* Handles dragOver events.
* This is an implementation detail.
*/
public void dragOver(DropTargetEvent event) {
Point point = tree.toControl(new Point(event.x, event.y));
// Get the item directly under the point
TreeItem item = tree.getItem(point);
if (item == null) return;
// Determine scroll direction according to whether we're nearer the top, middle, or bottom
Rectangle clientArea = tree.getClientArea();
int scrollRegionSize = Math.min(clientArea.height / 3, 24); // cut region into 3 parts
if (scrollRegionSize < 8) return; // don't scroll if the control is too small to make sense
TreeItem showItem = item;
for (;;) {
if (point.y < clientArea.y + scrollRegionSize) {
// in upper region
showItem = getPreviousVisibleItem(tree, showItem);
} else if (point.y > clientArea.height + clientArea.y - scrollRegionSize) {
// in lower region
showItem = getNextVisibleItem(tree, showItem, false);
} else {
// in middle region
break;
}
// Show the item (causes a scroll if it is outside of the visible region)
if (showItem == null) break;
tree.showItem(showItem);
// Test that we actually scrolled, if we didn't try again with the next item
if (item != tree.getItem(point)) break;
}
}
/**
* Given a TreeItem, locates its last (lowest) visible item
* <p>
* Note that the item may not be actually rendered onscreen though it would be
* visible were the control scrolled appropriately.
* </p>
*
* @param item the TreeItem whose last visible child is to be found
* @return the last visible child, or <code>item</code> if no visible children.
*/
private TreeItem getLastVisibleChild(TreeItem item) {
if (!item.getExpanded()) return item;
TreeItem[] items = item.getItems();
if (items == null || items.length == 0) return item;
return getLastVisibleChild(items[items.length - 1]);
}
/**
* Given a TreeItem, locates the following (below the specified item) visible TreeItem in a tree.
* <p>
* Note that the item may not be actually rendered onscreen though it would be
* visible were the control scrolled appropriately.
* </p>
*
* @param tree the Tree containing the items
* @param item the TreeItem whose next visible neighbour is to be found
* @return the next visible item, or null if none.
*/
private TreeItem getNextVisibleItem(Tree tree, TreeItem item, boolean ignoreChildren) {
TreeItem parent = item.getParentItem();
TreeItem[] items = (parent != null) ? parent.getItems() : tree.getItems();
if (items != null) {
for (int i = 0; i < items.length; ++i) {
if (items[i] == item) {
if (!ignoreChildren && items[i].getExpanded()) {
TreeItem[] children = items[i].getItems();
if (children != null && children.length > 0) return children[0];
}
if (i + 1 < items.length) return items[i + 1];
break;
}
}
if (parent != null) return getNextVisibleItem(tree, parent, true);
}
return null;
}
/**
* Given a TreeItem, locates the previous (above the specified item) visible TreeItem in a tree.
* <p>
* Note that the item may not be actually rendered onscreen though it would be
* visible were the control scrolled appropriately.
* </p>
*
* @param tree the Tree containing the items
* @param item the TreeItem whose previous visible neighbour is to be found
* @return the previous visible item, or null if none.
*/
private TreeItem getPreviousVisibleItem(Tree tree, TreeItem item) {
TreeItem parent = item.getParentItem();
TreeItem[] items = (parent != null) ? parent.getItems() : tree.getItems();
if (items != null) {
for (int i = items.length - 1; i > 0; --i) {
if (items[i] == item) return getLastVisibleChild(items[i - 1]);
}
}
return parent;
}
}

View file

@ -0,0 +1,359 @@
package org.eclipse.rse.files.importexport.files;
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.services.clientserver.messages.SystemMessageException;
import org.eclipse.rse.services.files.RemoteFileException;
import org.eclipse.rse.services.files.RemoteFileSecurityException;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
public class UniFilePlus extends File {
/**
*
*/
private static final long serialVersionUID = -1717648997950319457L;
public IRemoteFile remoteFile = null;
/**
* Constructor. There is only one way to construct this object,
* and that is by giving an IRemoteFile object. All java.io.File
* methods are intercepted and delegated to this contained object.
*/
public UniFilePlus(IRemoteFile remoteFile) {
super(remoteFile.getAbsolutePath());
this.remoteFile = remoteFile;
}
public boolean canRead() {
return remoteFile.canRead();
}
public boolean canWrite() {
return remoteFile.canWrite();
}
public int compareTo(File pathname) {
if (pathname instanceof UniFilePlus) return remoteFile.compareTo(pathname);
return super.compareTo(pathname);
}
/*
public int compareTo(Object o)
{
return remoteFile.compareTo(o);
}
*/
public boolean createNewFile() throws IOException {
IRemoteFile newFile = null;
try {
newFile = remoteFile.getParentRemoteFileSubSystem().createFile(remoteFile);
} catch (RemoteFileException exc) {
Exception e = exc.getRemoteException();
if (e != null) {
if (e instanceof SecurityException)
throw (SecurityException) e;
else if (e instanceof IOException) throw (IOException) e;
}
if (exc instanceof RemoteFileSecurityException)
throw new SecurityException(exc.getMessage());
else
throw new IOException(exc.getMessage());
}
if (newFile != null) {
remoteFile = newFile;
return true;
} else
return false;
}
public boolean delete() {
boolean ok = true;
try {
ok = remoteFile.getParentRemoteFileSubSystem().delete(remoteFile, null);
//hmm, should we set remoteFile to null?
} catch (RemoteFileException exc) {
Exception e = exc.getRemoteException();
if ((e != null) && (e instanceof SecurityException)) throw (SecurityException) e;
throw new SecurityException(exc.getMessage());
}
return ok;
}
/**
* NOT SUPPORTED!
*/
public void deleteOnExit() {
}
public boolean equals(Object obj) {
return remoteFile.equals(obj);
}
public boolean exists() {
return remoteFile.exists();
}
public File getAbsoluteFile() {
return this; // Remote File objects are always absolute!
}
public String getAbsolutePath() {
return remoteFile.getAbsolutePath();
}
public File getCanonicalFile() {
// hmm, maybe we should equal getAbsolutePathPlusConnection as canonical!
return this;
}
public String getCanonicalPath() {
return remoteFile.getAbsolutePathPlusConnection();
}
public String getName() {
return remoteFile.getName();
}
public String getParent() {
return remoteFile.getParentPath();
}
public File getParentFile() {
IRemoteFile parent = remoteFile.getParentRemoteFile();
if (parent != null) {
return new File(parent.getAbsolutePath());
//return parent.getFileWrapper();
} else
return null;
}
public String getPath() {
return remoteFile.getAbsolutePath();
}
public int hashCode() {
return remoteFile.getAbsolutePathPlusConnection().hashCode();
}
public boolean isAbsolute() {
return true;
}
public boolean isDirectory() {
return remoteFile.isDirectory();
}
public boolean isFile() {
return remoteFile.isFile();
}
public boolean isHidden() {
return remoteFile.isHidden();
}
public long lastModified() {
return remoteFile.getLastModified();
}
public long length() {
return remoteFile.getLength();
}
/**
* Returns an array of remote files that are children of this folder.
* This will be an null if there is an error or if the target object
* is not a folder.
* @return the array of IRemoteFiles.
*/
public IRemoteFile[] listIRemoteFiles() {
IRemoteFile[] result = null;
try {
result = remoteFile.getParentRemoteFileSubSystem().listFoldersAndFiles(remoteFile, getNullMonitor());
} catch (SystemMessageException e) {
SystemBasePlugin.logError("unexpected exception", e); //$NON-NLS-1$
}
return result;
}
public String[] list() {
IRemoteFile[] files = null;
try {
files = remoteFile.getParentRemoteFileSubSystem().listFoldersAndFiles(remoteFile, getNullMonitor());
} catch (SystemMessageException e) {
SystemBasePlugin.logError("unexpected exception", e); //$NON-NLS-1$
}
if (files != null) {
String[] fileNames = new String[files.length];
for (int idx = 0; idx < files.length; idx++)
fileNames[idx] = files[idx].getName();
return fileNames;
} else
return null;
}
public String[] list(FilenameFilter filter) {
IRemoteFile[] files = null;
try {
files = remoteFile.getParentRemoteFileSubSystem().listFoldersAndFiles(remoteFile, getNullMonitor());
} catch (SystemMessageException e) {
SystemBasePlugin.logError("unexpected exception", e); //$NON-NLS-1$
}
if (files != null) {
Vector v = new Vector();
String fileName = null;
for (int idx = 0; idx < files.length; idx++) {
fileName = files[idx].getName();
if ((fileName != null) && (filter.accept(this, fileName))) v.addElement(fileName);
}
String[] fileNames = new String[v.size()];
for (int idx = 0; idx < v.size(); idx++)
fileNames[idx] = (String) v.elementAt(idx);
return fileNames;
} else
return null;
}
public File[] listFiles(FileFilter filter) {
IRemoteFile[] files = null;
try {
files = remoteFile.getParentRemoteFileSubSystem().listFoldersAndFiles(remoteFile, getNullMonitor());
} catch (SystemMessageException e) {
SystemBasePlugin.logError("unexpected exception", e); //$NON-NLS-1$
}
if (files != null) {
Vector v = new Vector();
for (int idx = 0; idx < files.length; idx++) {
//fileName = files[idx].getName();
File fileObj = new File(files[idx].getAbsolutePath());
if (filter.accept(fileObj)) v.addElement(fileObj);
}
File[] fileObjs = new File[v.size()];
for (int idx = 0; idx < v.size(); idx++)
fileObjs[idx] = (File) v.elementAt(idx);
return fileObjs;
} else
return null;
}
public File[] listFiles(FilenameFilter filter) {
IRemoteFile[] files = null;
try {
files = remoteFile.getParentRemoteFileSubSystem().listFoldersAndFiles(remoteFile, getNullMonitor());
} catch (SystemMessageException e) {
SystemBasePlugin.logError("unexpected exception", e); //$NON-NLS-1$
}
if (files != null) {
Vector v = new Vector();
String fileName = null;
for (int idx = 0; idx < files.length; idx++) {
fileName = files[idx].getName();
if ((fileName != null) && (filter.accept(this, fileName))) v.addElement(files[idx]);
}
File[] fileObjs = new File[v.size()];
for (int idx = 0; idx < v.size(); idx++) {
fileObjs[idx] = new File(((IRemoteFile) v.elementAt(idx)).getAbsolutePath());
}
return fileObjs;
} else
return null;
}
public boolean mkdir() {
IRemoteFile dir = null;
try {
if (!remoteFile.exists()) dir = remoteFile.getParentRemoteFileSubSystem().createFolder(remoteFile);
} catch (RemoteFileException exc) {
Exception e = exc.getRemoteException();
if ((e != null) && (e instanceof SecurityException)) throw (SecurityException) e;
throw new SecurityException(exc.getMessage());
}
if (dir != null) remoteFile = dir;
return (dir != null);
}
public boolean mkdirs() {
IRemoteFile dir = null;
try {
if (!remoteFile.exists()) dir = remoteFile.getParentRemoteFileSubSystem().createFolder(remoteFile);
} catch (RemoteFileException exc) {
Exception e = exc.getRemoteException();
if ((e != null) && (e instanceof SecurityException)) throw (SecurityException) e;
throw new SecurityException(exc.getMessage());
}
if (dir != null) remoteFile = dir;
return (dir != null);
}
public boolean renameTo(File dest) {
boolean ok = false;
try {
ok = remoteFile.getParentRemoteFileSubSystem().rename(remoteFile, dest.getName());
} catch (RemoteFileException exc) {
Exception e = exc.getRemoteException();
if ((e != null) && (e instanceof SecurityException)) throw (SecurityException) e;
throw new SecurityException(exc.getMessage());
}
return ok;
}
public boolean setLastModified(long time) {
boolean ok = false;
if (time < 0) throw new IllegalArgumentException();
try {
IProgressMonitor monitor = new NullProgressMonitor();
ok = remoteFile.getParentRemoteFileSubSystem().setLastModified(monitor, remoteFile, time);
} catch (RemoteFileException exc) {
Exception e = exc.getRemoteException();
if ((e != null) && (e instanceof SecurityException)) throw (SecurityException) e;
throw new SecurityException(exc.getMessage());
}
return ok;
}
public boolean setReadOnly() {
boolean ok = false;
try {
ok = remoteFile.getParentRemoteFileSubSystem().setReadOnly(new NullProgressMonitor(), remoteFile, true);
} catch (RemoteFileException exc) {
Exception e = exc.getRemoteException();
if ((e != null) && (e instanceof SecurityException)) throw (SecurityException) e;
throw new SecurityException(exc.getMessage());
}
return ok;
}
public String toString() {
return getPath();
}
public URL toURL() throws MalformedURLException {
String urlName = "file://" + remoteFile.getAbsolutePathPlusConnection().replace('\\', '/'); //$NON-NLS-1$
if (remoteFile.isDirectory() && !urlName.endsWith("/")) //$NON-NLS-1$
urlName = urlName + '/';
return new URL(urlName);
}
private IProgressMonitor getNullMonitor() {
IProgressMonitor result = new NullProgressMonitor();
return result;
}
}

View file

@ -0,0 +1,226 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.files.importexport.files;
import org.eclipse.rse.core.SystemBasePlugin;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.files.importexport.IRemoteImportExportConstants;
import org.eclipse.rse.services.clientserver.messages.SystemMessage;
import org.eclipse.rse.services.clientserver.messages.SystemMessageException;
import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem;
import org.eclipse.rse.ui.ISystemMessages;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.ui.messages.SystemMessageDialog;
import org.eclipse.swt.widgets.Shell;
/**
* Contains several helper methods.
* A lot of these should really be provided by comm. layer, but for
* many reasons they were not. oh well ....
*/
public class Utilities implements IRemoteImportExportConstants {
public static final String IMPORT_DESCRIPTION_EXTENSION = REMOTE_FILE_IMPORT_DESCRIPTION_FILE_EXTENSION;
public static final String EXPORT_DESCRIPTION_EXTENSION = REMOTE_FILE_EXPORT_DESCRIPTION_FILE_EXTENSION;
/**
* Use this method to get IRemoteFile object from SystemConnection, and path
*
*/
public static IRemoteFile getIRemoteFile(IHost c, String path) {
IRemoteFile ret = null;
if (c != null) {
try {
IRemoteFileSubSystem ss = RemoteFileUtility.getFileSubSystem(c);
ret = ss.getRemoteFileObject(path);
} catch (SystemMessageException e) {
// get RemoteFileObject has been changed to raise
// SystemMessageException.
error(e);
}
}
return ret;
}
/**
* Use this method to get selected string from an
* IRemoteFile object.
*/
public static String getAsString(IRemoteFile selectedDirectory) {
return selectedDirectory.getSystemConnection().getSystemProfileName() + '.' + selectedDirectory.getSystemConnection().getAliasName() + ":" + selectedDirectory.getAbsolutePath(); //$NON-NLS-1$
}
/**
* Use this method to get selected string from an
* UniFilePlus object.
*/
public static String getAsString(UniFilePlus selectedDirectory) {
return selectedDirectory.remoteFile.getSystemConnection().getSystemProfileName() + '.' + selectedDirectory.remoteFile.getSystemConnection().getAliasName() + ":" + selectedDirectory.getPath(); //$NON-NLS-1$
}
/**
* Validate remote connection, and issue error if required.
*
*/
public static boolean isConnectionValid(String name, Shell s) {
boolean ret = true;
IHost sc = parseForSystemConnection(name);
if (sc == null) {
// invalid connection
ret = false;
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_IMPORT_EXPORT_UNABLE_TO_USE_CONNECTION);
SystemMessageDialog.show(s, msg);
//displayMessage(s, ISystemMessages.MSG_IMPORT_EXPORT_UNABLE_TO_USE_CONNECTION, true);
}
return ret;
}
/**
* Use this method to retrieve an IRemoteFile object from a
* selection string.
*/
public static IRemoteFile parseForIRemoteFile(String sel) {
IHost c = parseForSystemConnection(sel);
if (c != null) {
String path = parseForPath(sel);
return getIRemoteFile(c, path);
} else
return null;
}
/**
* Use this method to retrieve the file path from a
* selection string.
*/
public static String parseForPath(String sel) {
return sel.indexOf(":") >= 0 ? sel.substring(sel.indexOf(":") + 1) : sel; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Use this method to retrieve a SystemConnection from profile and a
* connectionName string.
*/
public static IHost getConnection(String profileName, String connectionName) {
IHost[] connections = RSEUIPlugin.getTheSystemRegistry().getHosts();
if (profileName != null) {
// given both profile and connection name...
for (int loop = 0; loop < connections.length; loop++) {
if (connections[loop].getAliasName().equalsIgnoreCase(connectionName) && connections[loop].getSystemProfileName().equalsIgnoreCase(profileName)) return connections[loop];
}
} else
// given only connection name...
for (int loop = 0; loop < connections.length; loop++) {
if (connections[loop].getAliasName().equalsIgnoreCase(connectionName)) return connections[loop]; // return 1st match
}
return null;
}
/**
* Use this method to retrieve a SystemConnection from a
* selection string. Should really be a part of RSE. If
* multiple separators ('.') are encountered will try
* profile names with 0,1,2,...n separators in order until a
* valid connection is found, or we run out of options.
*
* Not perfect, for example will never return connection C for
* profile one.two.three, if connection three.C for profile one.two
* exists. But this scheme should work fine for most practical
* cases.
*
* Wish RSE had chosen a separator that could not be part of
* valid connection name.
*/
public static IHost parseForSystemConnection(String sel) {
try {
// Assumption: following will return null if connection has
// been deleted or renamed!
String connectionName = sel.substring(0, sel.indexOf(":")); //$NON-NLS-1$
if (connectionName.indexOf('.') < 0)
return getConnection(null, connectionName);
else {
// iterate through all possible combinations until we find a match, or
// run out of options
int dots = 0, temp = 0;
IHost sc = null;
while (connectionName.indexOf('.', temp) >= 0) {
dots++;
temp = connectionName.indexOf('.', temp) + 1;
sc = getConnection(connectionName.substring(0, temp - 1), connectionName.substring(temp));
if (sc != null) return sc;
}
// did not find any, last hope try no profile, and '.' in name
return getConnection(null, connectionName);
}
} catch (Exception e) {
// Received exception while validating string.
// Ignore exception, just return null on fall-thru
}
// Connection with specified name was not found
return null;
}
// generic classes:
public static void error(Exception e) {
Object[] o = null;
// While developing launch configuration work we noticed that
// we could enter here with no access to a Shell object. Changed
// this method to simply log the exception in such cases.
Shell s = getShell();
try {
s = SystemBasePlugin.getActiveWorkbenchWindow().getShell();
} catch (Exception e1) {
s = null;
}
if (SystemMessageException.class.isInstance(e)) {
String mID = ((SystemMessageException) e).getSystemMessage().getFullMessageID().substring(0, 8);
Debug.out("About to issue SystemMessageException for " + mID); //$NON-NLS-1$
if (mID.compareToIgnoreCase("EVFC9104") != 0 && mID.compareToIgnoreCase("EVFC9112") != 0) { //$NON-NLS-1$ //$NON-NLS-2$
// As per DY, do not issue 9104, or 9112 messages; they must have already been issued!
if (s != null) {
SystemMessageDialog d = new SystemMessageDialog(s, ((SystemMessageException) e).getSystemMessage());
d.open();
}
}
} else {
o = new Object[] { e.getLocalizedMessage() == null ? e.toString() : e.getLocalizedMessage() };
logExceptionError(ISystemMessages.MSG_IMPORT_EXPORT_UNEXPECTED_EXCEPTION, o, e);
if (s != null) {
//displayMessage(s, ISystemMessages.MSG_IMPORT_EXPORT_UNEXPECTED_EXCEPTION, o, false);
SystemMessage msg = RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_IMPORT_EXPORT_UNEXPECTED_EXCEPTION);
msg.makeSubstitution(o[0]);
SystemMessageDialog.show(s, msg);
}
}
}
public static Shell getShell() {
Shell s = null;
try {
s = SystemBasePlugin.getActiveWorkbenchWindow().getShell();
} catch (Exception e1) {
s = null;
}
return s;
}
public static void logExceptionError(String msgId, Throwable exception) {
String msg = msgId + " " + RSEUIPlugin.getPluginMessage(msgId).getLevelOneText(); //$NON-NLS-1$
SystemBasePlugin.logError(msg, exception);
}
public static void logExceptionError(String msgId, Object[] subs, Throwable exception) {
SystemMessage sysMsg = RSEUIPlugin.getPluginMessage(msgId);
sysMsg.makeSubstitution(subs);
String msg = msgId + " " + sysMsg.getLevelOneText(); //$NON-NLS-1$
SystemBasePlugin.logError(msg, exception);
}
}

View file

@ -0,0 +1,64 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.importexport;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The main plugin class to be used in the desktop.
*/
public class RemoteImportExportPlugin extends AbstractUIPlugin {
//The shared instance.
private static RemoteImportExportPlugin plugin;
/**
* The constructor.
*/
public RemoteImportExportPlugin() {
super();
plugin = this;
}
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
super.stop(context);
plugin = null;
}
/**
* Returns the shared instance.
*/
public static RemoteImportExportPlugin getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path.
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.rse.importexport", path); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,89 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.importexport;
import org.eclipse.osgi.util.NLS;
public class SystemImportExportResources extends NLS {
private static String BUNDLE_NAME = "org.eclipse.rse.importexport.SystemImportExportResources";//$NON-NLS-1$
public static String IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_MESSAGE;
public static String IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_TITLE;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_ABSOLUTE;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_EXISTING_CONTAINER;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_INVALID_EXTENSION;
public static String IMPORT_EXPORT_ERROR_DESCRIPTION_NO_CONTAINER;
// REMOTE FILE EXPORT WIZARD...
public static String RESID_FILEEXPORT_TITLE;
public static String RESID_FILEEXPORT_PAGE1_TITLE;
public static String RESID_FILEEXPORT_PAGE1_DESCRIPTION;
public static String RESID_FILEEXPORT_DESTINATION_LABEL;
public static String RESID_FILEEXPORT_DESTINATION_TOOLTIP;
public static String RESID_FILEEXPORT_DESTINATION_BROWSE_LABEL;
public static String RESID_FILEEXPORT_DESTINATION_BROWSE_TOOLTIP;
public static String RESID_FILEEXPORT_OPTION_OVERWRITE_LABEL;
public static String RESID_FILEEXPORT_OPTION_OVERWRITE_TOOLTIP;
public static String RESID_FILEEXPORT_OPTION_CREATEALL_LABEL;
public static String RESID_FILEEXPORT_OPTION_CREATEALL_TOOLTIP;
public static String RESID_FILEEXPORT_OPTION_CREATESEL_LABEL;
public static String RESID_FILEEXPORT_OPTION_CREATESEL_TOOLTIP;
public static String RESID_FILEEXPORT_OPTION_SETTINGS_LABEL;
public static String RESID_FILEEXPORT_OPTION_SETTINGS_TOOLTIP;
public static String RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_LABEL;
public static String RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_PATH_TOOLTIP;
public static String RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_BROWSE_LABEL;
public static String RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_BROWSE_TOOLTIP;
public static String RESID_FILEEXPORT_OPTION_SETTINGS_DELTA_LABEL;
public static String RESID_FILEEXPORT_OPTION_SETTINGS_DELTA_TOOLTIP;
public static String RESID_FILEEXPORT_EXPORTING;
// REMOTE FILE IMPORT WIZARD...
public static String RESID_FILEIMPORT_TITLE;
public static String RESID_FILEIMPORT_PAGE1_TITLE;
public static String RESID_FILEIMPORT_PAGE1_DESCRIPTION;
public static String RESID_FILEIMPORT_OPTION_OVERWRITE_LABEL;
public static String RESID_FILEIMPORT_OPTION_OVERWRITE_TOOLTIP;
public static String RESID_FILEIMPORT_OPTION_CREATEALL_LABEL;
public static String RESID_FILEIMPORT_OPTION_CREATEALL_TOOLTIP;
public static String RESID_FILEIMPORT_OPTION_CREATESEL_LABEL;
public static String RESID_FILEIMPORT_OPTION_CREATESEL_TOOLTIP;
public static String RESID_FILEIMPORT_OPTION_SETTINGS_LABEL;
public static String RESID_FILEIMPORT_OPTION_SETTINGS_TOOLTIP;
public static String RESID_FILEIMPORT_OPTION_SETTINGS_DESCFILE_LABEL;
public static String RESID_FILEIMPORT_OPTION_SETTINGS_DESCFILE_PATH_TOOLTIP;
public static String RESID_FILEIMPORT_OPTION_SETTINGS_DESCFILE_BROWSE_LABEL;
public static String RESID_FILEIMPORT_OPTION_SETTINGS_DESCFILE_BROWSE_TOOLTIP;
public static String RESID_FILEIMPORT_SOURCE_LABEL;
public static String RESID_FILEIMPORT_SOURCE_TOOLTIP;
public static String RESID_FILEIMPORT_SOURCE_BROWSE_LABEL;
public static String RESID_FILEIMPORT_SOURCE_BROWSE_TOOLTIP;
public static String RESID_FILEIMPORT_IMPORTING;
public static String RESID_FILEIMPEXP_BUTTON_SELECTALL_LABEL;
public static String RESID_FILEIMPEXP_BUTTON_SELECTALL_TOOLTIP;
public static String RESID_FILEIMPEXP_BUTTON_DESELECTALL_LABEL;
public static String RESID_FILEIMPEXP_BUTTON_DESELECTALL_TOOLTIP;
public static String RESID_FILEIMPEXP_BUTTON_SELECTTYPES_LABEL;
public static String RESID_FILEIMPEXP_BUTTON_SELECTTYPES_TOOLTIP;
// REMOTE JAR EXPORT WIZARD
public static String RESID_RMTJAREXP_PREFIX;
public static String RESID_RMTJAREXP_FILEDIALOG_PREFIX;
public static String RESID_RMTJAREXP_FILEDIALOG_TITLE;
public static String RESID_RMTJAREXP_FILEDIALOG_PROMPT_LABEL;
public static String RESID_RMTJAREXP_FILEDIALOG_FILENAME_LABEL;
public static String RESID_RMTJAREXP_FILEDIALOG_FILENAME_TOOLTIP;
public static String RESID_RMTJAREXP_FILEDIALOG_FILETYPE_LABEL;
public static String RESID_RMTJAREXP_FILEDIALOG_FILETYPE_TOOLTIP;
public static String RESID_RMTJAREXP_SETTINGS_PREFIX;
public static String RESID_RMTJAREXP_SETTINGS_LABEL;
public static String RESID_RMTJAREXP_SETTINGS_TOOLTIP;
static {
// load message values from bundle file
NLS.initializeMessages(BUNDLE_NAME, SystemImportExportResources.class);
}
}

View file

@ -0,0 +1,122 @@
###############################################################################
# Copyright (c) 2000, 2007 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
# NLS_MESSAGEFORMAT_NONE
# NLS_ENCODING=UTF-8
#=============================================================
# REMOTE FILE EXPORT WIZARD...
#=============================================================
RESID_FILEEXPORT_TITLE=Export
RESID_FILEEXPORT_PAGE1_TITLE=Remote file system
RESID_FILEEXPORT_PAGE1_DESCRIPTION=Export resources to a remote file system.
RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_LABEL=Description file:
RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_PATH_TOOLTIP=Enter the description file path
RESID_FILEEXPORT_EXPORTING=Exporting:
RESID_FILEEXPORT_DESTINATION_LABEL=Destination folder, qualified by its remote connection name
RESID_FILEEXPORT_DESTINATION_TOOLTIP=Select the destination folder by browsing a remote system for it
RESID_FILEEXPORT_DESTINATION_BROWSE_LABEL=Browse...
RESID_FILEEXPORT_DESTINATION_BROWSE_TOOLTIP=Select the destination folder by browsing a remote system for it
RESID_FILEEXPORT_OPTION_OVERWRITE_LABEL=Overwrite existing files without warning
RESID_FILEEXPORT_OPTION_OVERWRITE_TOOLTIP=If a file being exported already exists remotely, replace it without a message
RESID_FILEEXPORT_OPTION_CREATEALL_LABEL=Create directory structure for files
RESID_FILEEXPORT_OPTION_CREATEALL_TOOLTIP=Create hierarchy (folder) structure in the file system as it exists in the Workbench
RESID_FILEEXPORT_OPTION_CREATESEL_LABEL=Create only selected directories
RESID_FILEEXPORT_OPTION_CREATESEL_TOOLTIP=Create hierarchy (folder) structure in the file system only for selected folders
RESID_FILEEXPORT_OPTION_SETTINGS_LABEL=Save the settings of this export in the workspace (e.g. /ExportSettings/hello.rexpfd)
RESID_FILEEXPORT_OPTION_SETTINGS_TOOLTIP=Save the export settings to a description file for quicker export in the future
RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_LABEL=Description file:
RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_PATH_TOOLTIP=Enter the description file path
RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_BROWSE_LABEL=Browse...
RESID_FILEEXPORT_OPTION_SETTINGS_DESCFILE_BROWSE_TOOLTIP=Specify the description file by browsing the workspace
RESID_FILEEXPORT_OPTION_SETTINGS_DELTA_LABEL=Export only changed resources
RESID_FILEEXPORT_OPTION_SETTINGS_DELTA_TOOLTIP=Export resources that have changed since last export when description file is used
#=============================================================
# REMOTE FILE IMPORT WIZARD...
#=============================================================
RESID_FILEIMPORT_TITLE=Import
RESID_FILEIMPORT_PAGE1_TITLE=Remote file system
RESID_FILEIMPORT_PAGE1_DESCRIPTION=Import resources from a remote file system.
RESID_FILEIMPORT_OPTION_SETTINGS_DESCFILE_LABEL=Description file:
RESID_FILEIMPORT_OPTION_SETTINGS_DESCFILE_PATH_TOOLTIP=Enter the description file path
RESID_FILEIMPORT_IMPORTING=Importing:
RESID_FILEIMPORT_OPTION_OVERWRITE_LABEL=Overwrite existing resources without warning
RESID_FILEIMPORT_OPTION_OVERWRITE_TOOLTIP=If a file being exported already exists remotely, replace it without a message
RESID_FILEIMPORT_OPTION_CREATEALL_LABEL=Create complete folder structure
RESID_FILEIMPORT_OPTION_CREATEALL_TOOLTIP=Create hierarchy (folder) structure in the Workbench, including parent folders
RESID_FILEIMPORT_OPTION_CREATESEL_LABEL=Create selected folders only
RESID_FILEIMPORT_OPTION_CREATESEL_TOOLTIP=Create hierarchy (folder) structure in the Workbench
RESID_FILEIMPORT_OPTION_SETTINGS_LABEL=Save the settings of this import in the workspace (e.g. /ImportSettings/hello.rimpfd)
RESID_FILEIMPORT_OPTION_SETTINGS_TOOLTIP=Save the import settings to a description file for quicker import in the future
RESID_FILEIMPORT_OPTION_SETTINGS_DESCFILE_BROWSE_LABEL=Browse...
RESID_FILEIMPORT_OPTION_SETTINGS_DESCFILE_BROWSE_TOOLTIP=Specify the description file by browsing the workspace
RESID_FILEIMPORT_SOURCE_LABEL=From directory:
RESID_FILEIMPORT_SOURCE_TOOLTIP=Source folder, qualified by its remote connection name
RESID_FILEIMPORT_SOURCE_BROWSE_LABEL=Browse...
RESID_FILEIMPORT_SOURCE_BROWSE_TOOLTIP=Select the source folder by browsing a remote system for it
RESID_FILEIMPEXP_BUTTON_SELECTALL_LABEL=Select All
RESID_FILEIMPEXP_BUTTON_SELECTALL_TOOLTIP=Select all resources
RESID_FILEIMPEXP_BUTTON_DESELECTALL_LABEL=Deselect All
RESID_FILEIMPEXP_BUTTON_DESELECTALL_TOOLTIP=De-select all resources
RESID_FILEIMPEXP_BUTTON_SELECTTYPES_LABEL=Select Types
RESID_FILEIMPEXP_BUTTON_SELECTTYPES_TOOLTIP=Select resource types to subset the selection list by
com.ibm.etools.systems.ui.FileImport.option.settings.descfile.label=Description file:
com.ibm.etools.systems.ui.FileImport.option.settings.descfile.path.tooltip=Enter the description file path
#=============================================================
# REMOTE JAR EXPORT WIZARD
#=============================================================
RESID_RMTJAREXP_FILEDIALOG_TITLE= Save As
RESID_RMTJAREXP_FILEDIALOG_PROMPT_LABEL= Specify or select a remote jar file
RESID_RMTJAREXP_FILEDIALOG_FILENAME_LABEL= File name
RESID_RMTJAREXP_FILEDIALOG_FILENAME_TOOLTIP= Enter the name of the jar file
RESID_RMTJAREXP_FILEDIALOG_FILETYPE_LABEL= Save as type
RESID_RMTJAREXP_FILEDIALOG_FILETYPE_TOOLTIP= Select the file type
RESID_RMTJAREXP_SETTINGS_LABEL=Save the settings of this jar export in the workspace (e.g. /ExportSettings/hello.rmtjardesc)
RESID_RMTJAREXP_SETTINGS_TOOLTIP=Save the jar export settings to a description file for quicker export in the future
IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_TITLE=
IMPORT_EXPORT_DESCRIPTION_FILE_DIALOG_MESSAGE=
IMPORT_EXPORT_ERROR_DESCRIPTION_ABSOLUTE=
IMPORT_EXPORT_ERROR_DESCRIPTION_EXISTING_CONTAINER=
IMPORT_EXPORT_ERROR_DESCRIPTION_NO_CONTAINER=
IMPORT_EXPORT_ERROR_DESCRIPTION_INVALID_EXTENSION=

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry path="src" kind="src"/>
<classpathentry path="org.eclipse.jdt.launching.JRE_CONTAINER" kind="con"/>
<classpathentry path="org.eclipse.pde.core.requiredPlugins" kind="con"/>
<classpathentry path="bin" kind="output"/>
</classpath>

View file

@ -0,0 +1 @@
bin

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.eclipse.rse.useractions</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,32 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %plugin.name
Bundle-SymbolicName: org.eclipse.rse.useractions;singleton:=true
Bundle-Version: 2.0.0
Bundle-Activator: org.eclipse.rse.useractions.Activator
Bundle-Localization: plugin
Require-Bundle: org.eclipse.core.resources,
org.eclipse.core.runtime,
org.eclipse.jface.text,
org.eclipse.ui,
org.eclipse.ui.views,
org.eclipse.ui.workbench.texteditor,
org.eclipse.ui.ide,
org.eclipse.rse.core,
org.eclipse.rse.services,
org.eclipse.rse.subsystems.shells.core,
org.eclipse.rse.subsystems.files.core,
org.eclipse.rse.shells.ui,
org.eclipse.rse.ui
Eclipse-LazyStart: true
Export-Package: org.eclipse.rse.useractions,
org.eclipse.rse.useractions.files.compile,
org.eclipse.rse.useractions.files.uda,
org.eclipse.rse.useractions.ui,
org.eclipse.rse.useractions.ui.compile,
org.eclipse.rse.useractions.ui.compile.teamview,
org.eclipse.rse.useractions.ui.propertypages,
org.eclipse.rse.useractions.ui.uda,
org.eclipse.rse.useractions.ui.uda.actions,
org.eclipse.rse.useractions.ui.uda.util
Bundle-Vendor: Eclipse.org

View file

@ -0,0 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>About</title>
</head>
<body lang="EN-US">
<h2>About This Content</h2>
<p>June 5, 2006</p>
<h3>License</h3>
<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;).
Unless otherwise indicated below, the Content is provided to you under the
terms and conditions of the Eclipse Public License Version 1.0 (&quot;EPL&quot;).
A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html.
For purposes of the EPL, &quot;Program&quot; will mean the Content.
</p>
<p>
If you did not receive this Content directly from the Eclipse Foundation,
the Content is being redistributed by another party (&quot;Redistributor&quot;) and different
terms and conditions may apply to your use of any object code in the Content.
Check the Redistributor’s license that was provided with the Content.
If no such license exists, contact the Redistributor.
Unless otherwise indicated below, the terms and conditions of the EPL still
apply to any source code in the Content and such source code may be obtained
at http://www.eclipse.org.
</p>
</body>
</html>

View file

@ -0,0 +1,17 @@
###############################################################################
# Copyright (c) 2002, 2007 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
plugin.xml,\
icons/,\
plugin.properties

Binary file not shown.

After

Width:  |  Height:  |  Size: 596 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 587 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 597 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 563 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 338 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 361 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 353 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 574 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 341 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 577 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 577 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 341 B

View file

@ -0,0 +1,15 @@
###############################################################################
# Copyright (c) 2002, 2007 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
# NLS_MESSAGEFORMAT_NONE
# NLS_ENCODING=UTF-8
plugin.name = RSE User Actions

View file

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
<!-- ============================================ -->
<!-- Define Workbench Properties Pages -->
<!-- ============================================ -->
<extension
point="org.eclipse.ui.propertyPages">
<page
objectClass="org.eclipse.rse.useractions.ui.uda.SystemUDActionElement"
name="%PropertyPage.TeamViewUserActionNode"
class="org.eclipse.rse.useractions.ui.propertypages.SystemTeamViewUserActionPropertyPage"
id="org.eclipse.rse.ui.SystemTeamViewUserActionPropertyPage">
</page>
<page
objectClass="org.eclipse.rse.useractions.ui.compile.teamview.SystemTeamViewCompileTypeNode"
name="%PropertyPage.TeamViewCompileTypeNode"
class="org.eclipse.rse.useractions.ui.propertypages.SystemTeamViewCompileTypePropertyPage"
id="org.eclipse.rse.ui.SystemTeamViewCompileTypePropertyPage">
</page>
<page
objectClass="org.eclipse.rse.useractions.ui.compile.teamview.SystemTeamViewCompileCommandNode"
name="%PropertyPage.TeamViewCompileCommandNode"
class="org.eclipse.rse.useractions.ui.propertypages.SystemTeamViewCompileCommandPropertyPage"
id="com.ibm.etools.systems.SystemTeamViewCompileCommandPropertyPage">
</page>
</extension>
</plugin>

View file

@ -0,0 +1,63 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The main plugin class to be used in the desktop.
*/
public class Activator extends AbstractUIPlugin {
//The shared instance.
private static Activator plugin;
/**
* The constructor.
*/
public Activator() {
plugin = this;
}
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
super.stop(context);
plugin = null;
}
/**
* Returns the shared instance.
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path.
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.rse.useractions", path); //$NON-NLS-1$
}
}

View file

@ -0,0 +1,116 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
/**
* Defines the standard icons for user actions, user types, and compile commands.
* Images and image descriptions may be extracted from these.
* There is no public constructor. Use the predefined instances of this class
* to access the images and descriptors.
*/
public class UserActionsIcon {
/**
* A new user defined action.
*/
public static final UserActionsIcon USERACTION_NEW = new UserActionsIcon("user_action_new_obj"); //$NON-NLS-1$
/**
* An existing user defined user action.
*/
public static final UserActionsIcon USERACTION_USR = new UserActionsIcon("user_action_obj"); //$NON-NLS-1$
/**
* A predefined user defined action.
*/
public static final UserActionsIcon USERACTION_IBM = new UserActionsIcon("user_action_ibm_obj"); //$NON-NLS-1$
/**
* A predefined user defined action that has been modified.
*/
public static final UserActionsIcon USERACTION_IBMUSR = new UserActionsIcon("user_action_ibm_user_obj"); //$NON-NLS-1$
/**
* A new user defined type.
*/
public static final UserActionsIcon USERTYPE_NEW = new UserActionsIcon("user_type_new_obj"); //$NON-NLS-1$
/**
* An existing user defined type.
*/
public static final UserActionsIcon USERTYPE_USR = new UserActionsIcon("user_type_obj"); //$NON-NLS-1$
/**
* A predefined user defined type.
*/
public static final UserActionsIcon USERTYPE_IBM = new UserActionsIcon("user_type_ibm_obj"); //$NON-NLS-1$
/**
* A predefined user defined type that has been modified.
*/
public static final UserActionsIcon USERTYPE_IBMUSR = new UserActionsIcon("user_type_ibm_user_obj"); //$NON-NLS-1$
/**
* A new user defined compile command.
*/
public static final UserActionsIcon COMPILE_NEW = new UserActionsIcon("compcmd_new_obj"); //$NON-NLS-1$
/**
* An existing user defined compile command.
*/
public static final UserActionsIcon COMPILE_USR = new UserActionsIcon("compcmd_user_obj"); //$NON-NLS-1$
/**
* A predefined user defined compile command.
*/
public static final UserActionsIcon COMPILE_IBM = new UserActionsIcon("compcmd_ibm_obj"); //$NON-NLS-1$
/**
* A predefined user defined compile command that has been edited.
*/
public static final UserActionsIcon COMPILE_IBMUSR = new UserActionsIcon("compcmd_ibmuser_obj"); //$NON-NLS-1$
private static final String PREFIX = "icon."; //$NON-NLS-1$
private static final String ICON_DIR = "icons/full/obj16/"; //$NON-NLS-1$
private static final String ICON_EXT = ".gif"; //$NON-NLS-1$
private String name;
private String id;
private String location;
private UserActionsIcon(String name) {
this.name = name;
this.id = PREFIX + name;
this.location = ICON_DIR + name + ICON_EXT;
}
/**
* Gets the image associated with this icon. This image is stored in the image registry of the
* user actions plugin and therefore the image must not be disposed when its use is completed.
* @return the image
*/
public Image getImage() {
ImageRegistry registry = Activator.getDefault().getImageRegistry();
Image image = registry.get(id);
if (image == null) {
ImageDescriptor descriptor = getImageDescriptor();
image = descriptor.createImage();
registry.put(id, image);
}
return image;
}
/**
* Gets the image descriptor associated with this icon.
* @return the image descriptor
*/
public ImageDescriptor getImageDescriptor() {
ImageDescriptor descriptor = Activator.getImageDescriptor(location);
return descriptor;
}
/**
* @return the name of the icon
*/
public String getName() {
return name;
}
}

View file

@ -0,0 +1,70 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions;
import org.eclipse.osgi.util.NLS;
public class UserActionsResources extends NLS {
private static String BUNDLE_NAME = "org.eclipse.rse.useractions.UserActionsResources"; //$NON-NLS-1$
// Property sheet values: Categories in Team view
public static String RESID_PROPERTY_TEAM_USERACTION_TYPE_VALUE;
public static String RESID_PROPERTY_TEAM_COMPILETYPE_TYPE_VALUE;
public static String RESID_PROPERTY_TEAM_COMPILECMD_TYPE_VALUE;
// USER ACTION PROPERTIES PAGE...
public static String RESID_PP_USERACTION_TITLE;
public static String RESID_PP_USERACTION_TYPE_VALUE;
public static String RESID_PP_USERACTION_PROFILE_LABEL;
public static String RESID_PP_USERACTION_PROFILE_TOOLTIP;
public static String RESID_PP_USERACTION_ORIGIN_LABEL;
public static String RESID_PP_USERACTION_ORIGIN_TOOLTIP;
public static String RESID_PP_USERACTION_DOMAIN_LABEL;
public static String RESID_PP_USERACTION_DOMAIN_TOOLTIP;
// COMPILE TYPE PROPERTIES PAGE...
public static String RESID_PP_COMPILETYPE_TITLE;
public static String RESID_PP_COMPILETYPE_TYPE_VALUE;
public static String RESID_PP_COMPILETYPE_TYPE_TOOLTIP;
public static String RESID_PP_COMPILETYPE_PROFILE_LABEL;
public static String RESID_PP_COMPILETYPE_PROFILE_TOOLTIP;
public static String RESID_PP_COMPILETYPE_FILETYPE_LABEL;
public static String RESID_PP_COMPILETYPE_FILETYPE_TOOLTIP;
// COMPILE COMMAND PROPERTIES PAGE...
public static String RESID_PP_COMPILECMD_TITLE;
public static String RESID_PP_COMPILECMD_TYPE_VALUE;
public static String RESID_PP_COMPILECMD_PROFILE_LABEL;
public static String RESID_PP_COMPILECMD_PROFILE_TOOLTIP;
public static String RESID_PP_COMPILECMD_ORIGIN_LABEL;
public static String RESID_PP_COMPILECMD_ORIGIN_TOOLTIP;
// USER ACTIONS
public static String ACTION_COMPILE_NOPROMPT_LABEL;
public static String ACTION_COMPILE_NOPROMPT_TOOLTIP;
public static String ACTION_COMPILE_PROMPT_LABEL;
public static String ACTION_COMPILE_PROMPT_TOOLTIP;
// Property sheet values: User actions
public static String RESID_PROPERTY_ORIGIN_IBM_VALUE;
public static String RESID_PROPERTY_ORIGIN_IBMUSER_VALUE;
public static String RESID_PROPERTY_ORIGIN_USER_VALUE;
public static String RESID_PROPERTY_ORIGIN_ISV_VALUE;
public static String RESID_PROPERTY_ORIGIN_ISVUSER_VALUE;
public static String RESID_PROPERTY_USERACTION_VENDOR_LABEL;
public static String RESID_PROPERTY_USERACTION_VENDOR_TOOLTIP;
public static String RESID_PROPERTY_USERACTION_DOMAIN_LABEL;
public static String RESID_PROPERTY_USERACTION_DOMAIN_TOOLTIP;
public static String RESID_PROPERTY_USERACTION_DOMAIN_ALL_VALUE;
// Property sheet values: Compile types
public static String RESID_PROPERTY_COMPILETYPE_TYPES_LABEL;
public static String RESID_PROPERTY_COMPILETYPE_TYPES_DESCRIPTION;
// TEAM VIEW
public static String RESID_TEAMVIEW_USERACTION_VALUE;
static {
// load message values from bundle file
NLS.initializeMessages(BUNDLE_NAME, UserActionsResources.class);
}
}

View file

@ -0,0 +1,85 @@
###############################################################################
# Copyright (c) 2002, 2007 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
# NLS_MESSAGEFORMAT_NONE
# NLS_ENCODING=UTF-8
#TEAM VIEW PROPERTIES
RESID_PROPERTY_TEAM_USERACTION_TYPE_VALUE=User action
RESID_PROPERTY_TEAM_COMPILETYPE_TYPE_VALUE=Compilable source type
RESID_PROPERTY_TEAM_COMPILECMD_TYPE_VALUE=Compile command
#=============================================================
# USER ACTION PROPERTIES PAGE...
#=============================================================
RESID_PP_USERACTION_TITLE=Properties for User Action
RESID_PP_USERACTION_TYPE_VALUE=User action
RESID_PP_USERACTION_PROFILE_LABEL=Parent profile
RESID_PP_USERACTION_PROFILE_TOOLTIP=Profile that contains this user action
RESID_PP_USERACTION_ORIGIN_LABEL=Origin
RESID_PP_USERACTION_ORIGIN_TOOLTIP=Who supplied this user action?
RESID_PP_USERACTION_DOMAIN_LABEL=Domain
RESID_PP_USERACTION_DOMAIN_TOOLTIP=What domain is this action scoped to?
#=============================================================
# COMPILE TYPE PROPERTIES PAGE...
#=============================================================
RESID_PP_COMPILETYPE_TITLE=Properties for Compilable Source Type
RESID_PP_COMPILETYPE_TYPE_VALUE=Compilable source type
RESID_PP_COMPILETYPE_TYPE_TOOLTIP=What type of artifact is this?
RESID_PP_COMPILETYPE_PROFILE_LABEL=Parent profile
RESID_PP_COMPILETYPE_PROFILE_TOOLTIP=Profile that contains this compile type and its compile commands
RESID_PP_COMPILETYPE_FILETYPE_LABEL=Source type
RESID_PP_COMPILETYPE_FILETYPE_TOOLTIP=The type of source that this type's compile commands apply to
#=============================================================
# COMPILE COMMAND PROPERTIES PAGE...
#=============================================================
RESID_PP_COMPILECMD_TITLE=Properties for Compilable Command
RESID_PP_COMPILECMD_TYPE_VALUE=Compile command
RESID_PP_COMPILECMD_PROFILE_LABEL=Parent profile
RESID_PP_COMPILECMD_PROFILE_TOOLTIP=Profile that contains this compile command
RESID_PP_COMPILECMD_ORIGIN_LABEL=Origin
RESID_PP_COMPILECMD_ORIGIN_TOOLTIP=Who supplied this compile command?
#=============================================================
# USER ACTIONS...
#=============================================================
ACTION_COMPILE_NOPROMPT_LABEL=Compile
ACTION_COMPILE_NOPROMPT_TOOLTIP=Run compile commands without prompting them
ACTION_COMPILE_PROMPT_LABEL=Compile (Prompt)
ACTION_COMPILE_PROMPT_TOOLTIP=Prompt and then run compile commands
#=============================================================
#USER ACTION PROPERTIES - PROPERTY SHEET
#=============================================================
RESID_PROPERTY_ORIGIN_IBM_VALUE=IBM supplied
RESID_PROPERTY_ORIGIN_IBMUSER_VALUE=IBM supplied, user edited
RESID_PROPERTY_ORIGIN_ISV_VALUE=ISV supplied
RESID_PROPERTY_ORIGIN_ISVUSER_VALUE=ISV supplied, user edited
RESID_PROPERTY_ORIGIN_USER_VALUE=User defined
RESID_PROPERTY_USERACTION_DOMAIN_ALL_VALUE=All
RESID_PROPERTY_USERACTION_VENDOR_LABEL=Vendor
RESID_PROPERTY_USERACTION_VENDOR_TOOLTIP=Vendor that supplied this command
RESID_PROPERTY_USERACTION_DOMAIN_LABEL=Domain
RESID_PROPERTY_USERACTION_DOMAIN_TOOLTIP=Object domain this applies to
#=============================================================
#COMPILE TYPE PROPERTIES - PROPERTY SHEET
#=============================================================
RESID_PROPERTY_COMPILETYPE_TYPES_LABEL=File type
RESID_PROPERTY_COMPILETYPE_TYPES_DESCRIPTION=File type this refers to
#=============================================================
# Team View
#=============================================================
RESID_TEAMVIEW_USERACTION_VALUE=User action

View file

@ -0,0 +1,46 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions.files.compile;
import org.eclipse.rse.core.model.ISystemProfile;
import org.eclipse.rse.useractions.ui.SystemCmdSubstVarList;
import org.eclipse.rse.useractions.ui.compile.SystemCompileProfile;
/**
* Specialization of the compile manager for universal files, for local files.
*/
public class LocalCompileManager extends UniversalCompileManager {
/**
* Constructor for LocalCompileManager.
*/
public LocalCompileManager() {
super();
}
/**
* Overridable method to instantiate the SystemCompileProfile for the
* given system profile.
* <p>
* We return an instance of LocalCompileProfile
*/
protected SystemCompileProfile createCompileProfile(ISystemProfile profile) {
return new LocalCompileProfile(this, profile.getName());
}
/**
* For support of the Work With Compile Commands dialog.
* <p>
* Return the substitution variables supported by compile commands managed by this manager.
*/
public SystemCmdSubstVarList getSubstitutionVariableList() {
return UniversalCompileSubstList.getSingleton();
}
}

View file

@ -0,0 +1,28 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions.files.compile;
import org.eclipse.rse.useractions.ui.compile.SystemCompileManager;
/**
* Specialization of the compile profile class, uniquely for the compile support of files from
* the local file subsystem.
*/
public class LocalCompileProfile extends UniversalCompileProfile {
/**
* Constructor
* @param manager
* @param profileName
*/
public LocalCompileProfile(SystemCompileManager manager, String profileName) {
super(manager, profileName);
}
}

View file

@ -0,0 +1,46 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions.files.compile;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.rse.shells.ui.RemoteCommandHelpers;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
import org.eclipse.rse.useractions.ui.compile.SystemCompilableSource;
import org.eclipse.rse.useractions.ui.compile.SystemCompileCommand;
import org.eclipse.swt.widgets.Shell;
/**
* This encapsulates a file in a universal file system, which is to be compiled.
*/
public class UniversalCompilableSource extends SystemCompilableSource {
/**
* Constructor for UniversalCompilableSource.
* @param shell
* @param firstSelection
* @param compileCmd
* @param isPrompt
*/
public UniversalCompilableSource(Shell shell, Object firstSelection, SystemCompileCommand compileCmd, boolean isPrompt, Viewer viewer) {
super(shell, firstSelection, compileCmd, isPrompt, viewer);
}
/**
* After the substituting and the prompting, it is now time to the remote running of the
* fully resolved compile command. Do that here.
* <p>
* We use the RemoteCommandHelpers class to run it.
*/
protected boolean internalRunCompileCommand(String compileCmd) {
String path = RemoteCommandHelpers.getWorkingDirectory((IRemoteFile) firstSelection);
boolean ok = RemoteCommandHelpers.runUniversalCommand(shell, compileCmd, path, getCommandSubSystem(), true);
return ok;
}
}

View file

@ -0,0 +1,64 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions.files.compile;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.core.model.ISystemProfile;
import org.eclipse.rse.useractions.ui.SystemCmdSubstVarList;
import org.eclipse.rse.useractions.ui.compile.ISystemCompileCommandSubstitutor;
import org.eclipse.rse.useractions.ui.compile.SystemCompileManager;
import org.eclipse.rse.useractions.ui.compile.SystemCompileProfile;
import org.eclipse.rse.useractions.ui.compile.SystemDefaultCompileCommands;
/**
* Specializatio of compile support for universal file subsystems.
*/
public class UniversalCompileManager extends SystemCompileManager {
/**
* Constructor for UniversalCompileManager.
*/
public UniversalCompileManager() {
super();
}
/**
* Overridable method to instantiate the SystemCompileProfile for the
* given system profile.
* <p>
* We return an instance of UniversalCompileProfile
*/
protected SystemCompileProfile createCompileProfile(ISystemProfile profile) {
return new UniversalCompileProfile(this, profile.getName());
}
/**
* Return the default list of compile commands to prime new documents with.
*/
public SystemDefaultCompileCommands getDefaultCompileCommands() {
return UniversalIBMCompileCommands.getIBMCompileCommands();
}
/**
* For support of the Work With Compile Commands dialog.
* <p>
* Return the substitution variables supported by compile commands managed by this manager.
*/
public SystemCmdSubstVarList getSubstitutionVariableList() {
return UniversalCompileSubstList.getSingleton();
}
/**
* @see org.eclipse.rse.useractions.ui.compile.SystemCompileManager#createSubstitutor(IHost)
*/
protected ISystemCompileCommandSubstitutor createSubstitutor(IHost connection) {
return new UniversalCompileSubstitutor(connection);
}
}

View file

@ -0,0 +1,44 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions.files.compile;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.rse.useractions.ui.compile.SystemCompilableSource;
import org.eclipse.rse.useractions.ui.compile.SystemCompileCommand;
import org.eclipse.rse.useractions.ui.compile.SystemCompileManager;
import org.eclipse.rse.useractions.ui.compile.SystemCompileProfile;
import org.eclipse.swt.widgets.Shell;
/**
* Specialization of the compile profile class, uniquely for the compile support of files from
* a universal file subsystem.
*/
public class UniversalCompileProfile extends SystemCompileProfile {
/**
* Constructor for UniversalCompileProfile.
* @param manager
* @param profileName
*/
public UniversalCompileProfile(SystemCompileManager manager, String profileName) {
super(manager, profileName);
}
/**
* When the time comes to actually run a compile command against a selected source object,
* this method is called to return the instance of SystemCompilableSource to do that.
* <p>
* This method must be implemented to return an instance of your subclass of SystemCompilableSource.
*/
public SystemCompilableSource getCompilableSourceObject(Shell shell, Object selectedObject, SystemCompileCommand compileCmd, boolean isPrompt, Viewer viewer) {
UniversalCompilableSource compilableSrc = new UniversalCompilableSource(shell, selectedObject, compileCmd, isPrompt, viewer);
return compilableSrc;
}
}

View file

@ -0,0 +1,54 @@
package org.eclipse.rse.useractions.files.compile;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.rse.useractions.ui.SystemCmdSubstVarList;
import org.eclipse.rse.useractions.ui.uda.SystemUDAResources;
/**
* Encapsulation of the compile command substitution variables for universal files.
*/
public class UniversalCompileSubstList extends SystemCmdSubstVarList {
private static final String[] UNIVERSAL_FILES_VARNAMES = { "system_filesep", //$NON-NLS-1$
"system_homedir", //$NON-NLS-1$
"system_pathsep", //$NON-NLS-1$
"system_tempdir", //$NON-NLS-1$
"resource_name", //$NON-NLS-1$
"resource_name_root", //$NON-NLS-1$
"resource_path", //$NON-NLS-1$
"resource_path_root", //$NON-NLS-1$
"resource_path_drive", //$NON-NLS-1$
"container_name", //$NON-NLS-1$
"container_path" //$NON-NLS-1$
};
private static final String[] UNIVERSAL_FILES_DESCRIPTIONS = { SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_SYSTEM_FILESEP, SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_SYSTEM_HOMEDIR,
SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_SYSTEM_PATHSEP, SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_SYSTEM_TEMPDIR, SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_RESOURCE_NAME,
SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_RESOURCE_NAME_ROOT, SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_RESOURCE_PATH,
SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_RESOURCE_PATH_ROOT, SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_RESOURCE_PATH_DRIVE,
SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_CONTAINER_NAME, SystemUDAResources.RESID_COMPILE_FILES_SUBVAR_CONTAINER_PATH };
private static UniversalCompileSubstList inst = null;
/**
* Constructor .
* Not to be used directly. Rather, use getSingleton().
*/
UniversalCompileSubstList() {
super(UNIVERSAL_FILES_VARNAMES, UNIVERSAL_FILES_DESCRIPTIONS);
}
/**
* Return the singleton of this object. No need ever for more than one instance
*/
public static UniversalCompileSubstList getSingleton() {
if (inst == null) inst = new UniversalCompileSubstList();
return inst;
}
}

View file

@ -0,0 +1,218 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions.files.compile;
import org.eclipse.rse.core.SystemAdapterHelpers;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.shells.ui.RemoteCommandHelpers;
import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration;
import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteCmdSubSystem;
import org.eclipse.rse.useractions.ui.compile.ISystemCompileCommandSubstitutor;
/**
* This class is responsible for doing variable substitution for iSeries compile
* commands
*/
public class UniversalCompileSubstitutor implements ISystemCompileCommandSubstitutor {
private IHost connection;
/**
* Constructor for UniversalCompileSubstitutor.
*/
public UniversalCompileSubstitutor(IHost connection) {
super();
this.connection = connection;
}
/**
* Reset the connection so one instance can be re-used
*/
public void setConnection(IHost connection) {
this.connection = connection;
}
/**
* @see org.eclipse.rse.useractions.ui.ISystemSubstitutor#getSubstitutionValue(String, Object)
*/
public String getSubstitutionValue(String substitutionVariable, Object context) {
//private static final String[] UNIVERSAL_FILES_VARNAMES =
//{"system_filesep", "system_homedir", "system_pathsep", "system_tempdir",
// "user_id", "resource_name", "resource_path", "resource_path_root", "resource_path_drive", "container_name", "container_path"};
if (substitutionVariable.equals("${system_filesep}")) //$NON-NLS-1$
return getFileSeparator();
else if (substitutionVariable.equals("${system_homedir}")) //$NON-NLS-1$
return getHomeDirectory();
else if (substitutionVariable.equals("${system_pathsep}")) //$NON-NLS-1$
return getPathSeparator();
else if (substitutionVariable.equals("${system_tempdir}")) //$NON-NLS-1$
return getTempDirectory();
else if (substitutionVariable.equals("${user_id}")) //$NON-NLS-1$
return getUserId();
else if (substitutionVariable.equals("${resource_name}")) //$NON-NLS-1$
return getResourceName(context);
else if (substitutionVariable.equals("${resource_name_root}")) //$NON-NLS-1$
return getResourceNameRoot(context);
else if (substitutionVariable.equals("${resource_path}")) //$NON-NLS-1$
return getResourcePath(context);
else if (substitutionVariable.equals("${resource_path_root}")) //$NON-NLS-1$
return getPathRoot(context);
else if (substitutionVariable.equals("${resource_path_drive}")) //$NON-NLS-1$
return getPathDrive(context);
else if (substitutionVariable.equals("${container_name}")) //$NON-NLS-1$
return getContainerName(context);
else if (substitutionVariable.equals("${container_path}")) //$NON-NLS-1$
return getContainerPath(context);
return null;
}
/**
* Get the command subsystem
*/
protected IRemoteCmdSubSystem getCmdsSubSystem() {
return RemoteCommandHelpers.getCmdSubSystem(connection);
}
/**
* Get the files subsystem
*/
protected IRemoteFileSubSystem getFilesSubSystem() {
return RemoteFileUtility.getFileSubSystem(connection);
}
/**
* Get the files subsystem factory
*/
protected IRemoteFileSubSystemConfiguration getFilesSubSystemFactory() {
return RemoteFileUtility.getFileSubSystem(connection).getParentRemoteFileSubSystemConfiguration();
}
/**
* Return the file separator for the ${system_filesep} variable
*/
protected String getFileSeparator() {
return getFilesSubSystemFactory().getSeparator();
}
/**
* Return the path separator for the ${system_pathsep} variable
*/
protected String getPathSeparator() {
return getFilesSubSystemFactory().getPathSeparator();
}
/**
* Return the user's home directory on the remote system, for the ${system_homedir} variable
*/
protected String getHomeDirectory() {
return getCmdsSubSystem().getConnectorService().getHomeDirectory();
}
/**
* Return the temporary directory on the remote system, for the ${system_tempdir} variable
*/
protected String getTempDirectory() {
return getCmdsSubSystem().getConnectorService().getTempDirectory();
}
/**
* Return the user ID used to connect with the remote system, for the ${user_id} variable
*/
protected String getUserId() {
return getCmdsSubSystem().getConnectorService().getUserId();
}
/**
* Return the name of the currently selected resource, for the ${resource_name} variable
*/
protected String getResourceName(Object context) {
return SystemAdapterHelpers.getRemoteAdapter(context).getName(context);
}
/**
* Return the root part of the name of the currently selected resource, for the ${resource_name_root} variable
*/
protected String getResourceNameRoot(Object context) {
IRemoteFile selectedFile = (IRemoteFile) context;
String name = selectedFile.getName();
int dotIdx = name.lastIndexOf('.');
if (dotIdx == 0)
return ""; //$NON-NLS-1$
else if (dotIdx > 0)
return name.substring(0, dotIdx);
else
return name;
}
/**
* Return the path of the currently selected resource, for the ${resource_path} variable
*/
protected String getResourcePath(Object context) {
return SystemAdapterHelpers.getRemoteAdapter(context).getAbsoluteName(context);
}
/**
* Return the root part of the path, for the ${resource_path_root} variable
*/
protected String getPathRoot(Object context) {
IRemoteFile selectedFile = (IRemoteFile) context;
String name = selectedFile.getAbsolutePath();
if (name != null) {
if (name.startsWith("/") || name.startsWith("\\")) //$NON-NLS-1$ //$NON-NLS-2$
return name.substring(0, 1);
else {
int idx = name.indexOf(":\\"); //$NON-NLS-1$
if (idx > 0) return name.substring(0, idx + 2);
}
}
return ""; //$NON-NLS-1$
}
/**
* Return the drive part of the path, for the ${resource_path_drive} variable
*/
protected String getPathDrive(Object context) {
IRemoteFile selectedFile = (IRemoteFile) context;
String name = selectedFile.getAbsolutePath();
if ((name != null) && (name.length() > 1)) {
int idx = name.indexOf(':');
if (idx > 0) return name.substring(0, idx);
}
return ""; //$NON-NLS-1$
}
/**
* Return the name of the parent folder, for the ${container_name} variable
*/
protected String getContainerName(Object context) {
IRemoteFile selectedFile = (IRemoteFile) context;
String fn = selectedFile.getParentName();
if (fn != null)
return fn;
else
return ""; //$NON-NLS-1$
}
/**
* Return the path of the parent folder, for the ${container_path} variable
*/
protected String getContainerPath(Object context) {
IRemoteFile selectedFile = (IRemoteFile) context;
String name = selectedFile.getAbsolutePath();
if ((name != null) && (name.length() > 1)) {
int idx = name.indexOf(':');
if (idx > 0) return name.substring(0, idx);
}
return ""; //$NON-NLS-1$
}
}

View file

@ -0,0 +1,44 @@
package org.eclipse.rse.useractions.files.compile;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.rse.useractions.ui.compile.SystemDefaultCompileCommand;
/**
* Specialization of the the SystemDefaultCompileCommand for an IBM-supplied
* compile command for universal files.
*/
public class UniversalIBMCompileCommand extends SystemDefaultCompileCommand {
/**
* Constructor for UniversalCompileIBMCommand.
* @param commandLabel
* @param commandName
*/
public UniversalIBMCompileCommand(String commandLabel, String commandName) {
super(commandLabel, commandName);
}
/**
* Constructor for UniversalCompileIBMCommand.
* @param commandName
*/
public UniversalIBMCompileCommand(String commandName) {
super(commandName);
}
/**
* Constructor that takes a command name and label and the parameters.
* This avoids you having to call setAdditionalCommandParameters.
*/
public UniversalIBMCompileCommand(String commandLabel, String commandName, String parameters) {
super(commandLabel, commandName, parameters);
}
}

View file

@ -0,0 +1,65 @@
package org.eclipse.rse.useractions.files.compile;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.rse.useractions.ui.compile.SystemDefaultCompileCommands;
/**
* Specialization of the SystemDefaultCompileCommands for the IBM-supplied compile commands
* for universal files
*/
public class UniversalIBMCompileCommands extends SystemDefaultCompileCommands {
private static UniversalIBMCompileCommands ibmCompileCommands;
// Source types supported
public static final String TYPE_C = "c"; //$NON-NLS-1$
public static final String TYPE_CC = "cc"; //$NON-NLS-1$
public static final String TYPE_CXX = "cxx"; //$NON-NLS-1$
public static final String TYPE_CPP = "cpp"; //$NON-NLS-1$
public static final String TYPE_CPP_C = "C"; //$NON-NLS-1$
public static final String TYPE_CPP_CC = "CC"; //$NON-NLS-1$
public static final String TYPE_CPP_CXX = "CXX"; //$NON-NLS-1$
public static final String TYPE_JAVA = "java"; //$NON-NLS-1$
public static final String[] ALL_IBM_SRC_TYPES = { TYPE_C, TYPE_CPP, TYPE_CC, TYPE_CPP_CC, TYPE_CXX, TYPE_CPP_CXX, TYPE_JAVA };
/**
* Constructor
*/
public UniversalIBMCompileCommands() {
super();
}
/**
* Get all IBM supplied compilable source types.
*/
public String[] getAllDefaultSuppliedSourceTypes() {
return ALL_IBM_SRC_TYPES;
}
/**
* Return the singleton instance of the list of commands IBM recognizes by default
*/
public static UniversalIBMCompileCommands getIBMCompileCommands() {
if (ibmCompileCommands == null) {
ibmCompileCommands = new UniversalIBMCompileCommands();
UniversalIBMCompileCommand cmd = null;
cmd = new UniversalIBMCompileCommand("JAVAC", "javac", "-deprecation -classpath . ${resource_name}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
cmd.setSourceTypes(new String[] { TYPE_JAVA });
ibmCompileCommands.addCommand(cmd);
cmd = new UniversalIBMCompileCommand("GCC", "gcc", "-c ${resource_name} -o ${resource_name_root}.o"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
cmd.setSourceTypes(new String[] { TYPE_C, TYPE_CC, TYPE_CPP, TYPE_CPP_CC, TYPE_CPP_CXX, TYPE_CXX });
ibmCompileCommands.addCommand(cmd);
cmd = new UniversalIBMCompileCommand("CC", "cc", "-c ${resource_name} -o ${resource_name_root}.o"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
cmd.setSourceTypes(new String[] { TYPE_C, TYPE_CC, TYPE_CPP, TYPE_CPP_CC, TYPE_CPP_CXX, TYPE_CXX });
ibmCompileCommands.addCommand(cmd);
}
return ibmCompileCommands;
}
}

View file

@ -0,0 +1,783 @@
package org.eclipse.rse.useractions.files.uda;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.rse.core.model.ISystemProfile;
import org.eclipse.rse.core.subsystems.ISubSystem;
import org.eclipse.rse.core.subsystems.ISubSystemConfiguration;
import org.eclipse.rse.services.clientserver.FileTypeMatcher;
import org.eclipse.rse.shells.ui.RemoteCommandHelpers;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile;
import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem;
import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteCmdSubSystem;
import org.eclipse.rse.ui.ISystemIconConstants;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.useractions.UserActionsIcon;
import org.eclipse.rse.useractions.ui.SystemCmdSubstVarList;
import org.eclipse.rse.useractions.ui.uda.ISystemUDAEditPaneHoster;
import org.eclipse.rse.useractions.ui.uda.ISystemUDTreeView;
import org.eclipse.rse.useractions.ui.uda.SystemUDAResources;
import org.eclipse.rse.useractions.ui.uda.SystemUDActionElement;
import org.eclipse.rse.useractions.ui.uda.SystemUDActionManager;
import org.eclipse.rse.useractions.ui.uda.SystemUDActionSubsystem;
import org.eclipse.rse.useractions.ui.uda.SystemUDBaseManager;
import org.eclipse.rse.useractions.ui.uda.SystemUDTypeEditPane;
import org.eclipse.rse.useractions.ui.uda.SystemUDTypeElement;
import org.eclipse.rse.useractions.ui.uda.SystemUDTypeManager;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
/**
* User action subsystem for universal files
*/
public class UDActionSubsystemFiles extends SystemUDActionSubsystem {
public static final String NO_EXTENSION_PLACEHOLDER = ".null"; //$NON-NLS-1$
private static DateFormat dateFormatter;
// INSTANCE VARIABLES...
private FileTypeMatcher fileTypeMatcher;
// CONSTANTS...
private static final String DOMAINS[] = { "Folder", "File" }; //$NON-NLS-1$ //$NON-NLS-2$
// Matching name string in the plugin resources (translated)
//private String DOMAIN_NEWTYPENAME_STRING[] = { RESID_UDT_FILES_DOMAIN_NEWFOLDER, RESID_UDT_FILES_DOMAIN_NEWFILE };
// index values must match above 2 variables
public static final int DOMAIN_FOLDER = 0;
public static final int DOMAIN_FILE = 1;
protected static final String FILE_ACTIONS[][] = // todo!
// name, refresh, singleSel, collect, types, cmd
{ { "java", "false", "true", "false", "CLASS", "java ${resource_name_root}" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
{ "javac", "true", "false", "true", "JAVA", "javac -deprecation -classpath . ${resource_name}" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
{ "jar", "true", "false", "true", "ALL", "jar -cvf classes.jar ${resource_name}" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
{ "unjar", "false", "true", "false", "JAR ZIP", "jar -xf ${resource_name}" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
{ "gmake", "true", "false", "false", "GNU_MAKEFILE", "gmake -f ${resource_name}" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
{ "make", "true", "false", "false", "MAKEFILE", "make -f ${resource_name}" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
// I have decided against the following in favor of allowing these to be expanded in the tree view. Phil
//{"list", "false", "true", "false", "JAR ZIP", "jar tf ${resource_name}"},
};
protected static final String FOLDER_ACTIONS[][] =
// name, refresh, singleSel, collect, cmd
{ { "javac", "true", "false", "true", "javac -deprecation -classpath . *.java" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
{ "jar", "true", "false", "true", "jar cvf classes.jar *.class" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
};
protected static final String IBM_DEFAULT_FOLDERTYPES[][] = { // name, types
{ "ALL", "*" }, //$NON-NLS-1$ //$NON-NLS-2$
};
protected static final String IBM_DEFAULT_FILETYPES[][] = { // name, types
{ "ALL", "*" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "C", "c,h,i" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "C_COMPILABLE", "c" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "CPP", "cpp,cxx,hpp,ipp" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "CPP_COMPILABLE", "cpp,cxx" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "CLASS", "class" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "CSS", "css" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "EAR", "ear" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "EXE", "exe,bat,cmd" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "GRAPHIC", "bmp,gif,jpg" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "GNU_MAKEFILE", "GNUMakefile" + NO_EXTENSION_PLACEHOLDER }, //$NON-NLS-1$ //$NON-NLS-2$
{ "HTML", "htm, html" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "JAVA", "java" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "JAVASCRIPT", "js" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "JAR", "jar" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "JARZIP", "jar,zip" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "JSP", "jsp" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "MAKEFILE", "makefile" + NO_EXTENSION_PLACEHOLDER + ", mak" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
{ "NONE", "null" }, // our own invention! //$NON-NLS-1$ //$NON-NLS-2$
{ "PERL", "pl" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "PROFILE", "profile" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "PYTHON", "py" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "SHELL ", "csh, ksh, sh" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "SQLJ", "sqlj" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "WAR", "war" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "WEB", "css, htm, html, js, jsp" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "TAR", "tar" }, //$NON-NLS-1$ //$NON-NLS-2$
{ "ZIP", "zip" }, //$NON-NLS-1$ //$NON-NLS-2$
};
protected String[] DOMAIN_NAME_STRING = new String[2];
protected String[] DOMAIN_NEWNAME_STRING = new String[2];
/**
* Constructor
*/
public UDActionSubsystemFiles() {
super();
DOMAIN_NAME_STRING[0] = SystemUDAResources.RESID_UDA_FILES_DOMAIN_FOLDER;
DOMAIN_NAME_STRING[1] = SystemUDAResources.RESID_UDA_FILES_DOMAIN_FILE;
DOMAIN_NEWNAME_STRING[0] = SystemUDAResources.RESID_UDA_FILES_DOMAIN_NEWFOLDER;
DOMAIN_NEWNAME_STRING[1] = SystemUDAResources.RESID_UDA_FILES_DOMAIN_NEWFILE;
}
/**
* Overridable extension point for child classes to do migration of their actions.
* This is called on first load of a document, which has a release stamp other than
* the current release
* @return true if any migration was done... we return false
*/
protected boolean doActionsMigration(ISystemProfile profile, String oldRelease) {
return false;
}
/**
* Overridable extension point for child classes to do migration of their types.
* This is called on first load of a document, which has a release stamp other than
* the current release
* @return true if any migration was done... we return false
*/
protected boolean doTypesMigration(ISystemProfile profile, String oldRelease) {
return false;
}
/**
* Required override of parent for doing substitutions for our unique variables.
*/
public String internalGetSubstitutionValue(SystemUDActionElement currentAction, String subvar, Object selectedObject) {
return getUniversalSubstitutionValue(currentAction, subvar, selectedObject);
}
/**
* Required override of parent for doing substitutions for our unique variables.
*/
public static String getUniversalSubstitutionValue(SystemUDActionElement currentAction, String subvar, Object selectedObject) {
/* from resource property file...
Common to files and folders:
...uda.files.subvar.resource_date = Last modified date of selected resource
...uda.files.subvar.resource_name = Name of selected resource, unqualified
...uda.files.subvar.resource_path = Path of selected resource, including name
...uda.files.subvar.resource_path_root=Root of selected file's path. "c:\\" on Windows, or "/" on others
...uda.files.subvar.resource_path_drive=Drive letter on Windows, empty string on others
...uda.files.subvar.container_name=Name of folder containing selected resource, unqualified
...uda.files.subvar.container_path=Path of folder containing selected resource, including name
// note: resource_name and resource_path handled for us in parent class!
File specific:
...uda.files.subvar.resource_name_root=Name of selected resource without the extension
...uda.files.subvar.resource_name_ext=Extension part of the name of the selected resource
*/
IRemoteFile selectedFile = (IRemoteFile) selectedObject;
if (subvar.equals("${resource_date}")) //$NON-NLS-1$
{
if (dateFormatter == null) dateFormatter = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss z"); //new SimpleDateFormat(); //$NON-NLS-1$
Date lmd = selectedFile.getLastModifiedDate();
if (lmd != null)
return dateFormatter.format(lmd);
else
return "not available"; //$NON-NLS-1$
} else if (subvar.equals("${resource_name_root}")) //$NON-NLS-1$
{
String name = selectedFile.getName();
int dotIdx = name.lastIndexOf('.');
if (dotIdx == 0)
return ""; //$NON-NLS-1$
else if (dotIdx > 0)
return name.substring(0, dotIdx);
else
return name;
} else if (subvar.equals("${resource_name_ext}")) //$NON-NLS-1$
{
String name = selectedFile.getName();
int dotIdx = name.lastIndexOf('.');
if (dotIdx == 0) {
if (name.length() == 1)
return ""; //$NON-NLS-1$
else
return name.substring(1);
} else if (dotIdx > 0)
return name.substring(dotIdx + 1);
else
return ""; //$NON-NLS-1$
}
/*
else if (subvar.equals("${path}"))
{
String p = selectedFile.getParentNoRoot();
if (p != null)
return p;
else
return "";
}
*/
else if (subvar.equals("${container_name}")) //$NON-NLS-1$
{
// another example where the info can't be trusted!
/*
String fn = selectedFile.getParentName();
if (fn != null)
return fn;
else
return "";
*/
String fullpath = selectedFile.getParentPath();
if ((fullpath == null) || (fullpath.length() == 0)) return ""; //$NON-NLS-1$
IRemoteFileSubSystem rfss = getFileSubSystem(selectedObject);
if (rfss == null) return ""; //$NON-NLS-1$
char sep = rfss.getParentRemoteFileSubSystemConfiguration().getSeparatorChar();
int idx = fullpath.lastIndexOf(sep);
if (idx >= 0)
return fullpath.substring(idx + 1);
else
return ""; //$NON-NLS-1$
} else if (subvar.equals("${container_path}")) //$NON-NLS-1$
return selectedFile.getParentPath();
else if (subvar.equals("${resource_path_root}")) //$NON-NLS-1$
{
String name = selectedFile.getAbsolutePath();
if (name != null) {
if (name.startsWith("/") || name.startsWith("\\")) //$NON-NLS-1$ //$NON-NLS-2$
return name.substring(0, 1);
else {
int idx = name.indexOf(":\\"); //$NON-NLS-1$
if (idx > 0) return name.substring(0, idx + 2);
}
}
return ""; //$NON-NLS-1$
} else if (subvar.equals("${resource_path_drive}")) //$NON-NLS-1$
{
//String root = selectedFile.getRoot();
String name = selectedFile.getAbsolutePath();
if ((name != null) && (name.length() > 1)) {
int idx = name.indexOf(':');
if (idx > 0) return name.substring(0, idx);
}
return ""; //$NON-NLS-1$
}
/* now handled in common base class
else if (subvar.equals("${system_pathsep}"))
return selectedFile.getSeparator();
*/
return null; // return null to tell parent we didn't do any substitutions!
}
/**
* Get the delimiter used to delimiter the types in a type string.
* Default is " "
*/
protected String getTypesDelimiter() {
return ","; //$NON-NLS-1$
}
/**
* After an action's command has been resolved (vars substituted) this method
* is called to actually do the remote command execution
* <p>
* Run the user action's command in the default shell, and
* log result in the command view.
*
* @param shell - the shell to use if need to prompt for password or show msg dialog
* @param action - the action being processed, in case attributes of it need to be queried
* @param cmdString - the resolved command
* @param cmdSubSystem - this connection's command subsystem, which will run the command
* @param context - the selected IRemoteFile object
* @param viewer
* @return true if we should continue, false if something went wrong
*/
protected boolean runCommand(Shell shell, SystemUDActionElement action, String cmdString, IRemoteCmdSubSystem cmdSubSystem, Object context, Viewer viewer) {
return runUniversalCommand(shell, cmdString, cmdSubSystem, context);
}
/**
* Encapsulation of code needed to run a universal subsystem command.
*
* @param shell - the shell to use if need to prompt for password or show msg dialog
* @param cmdString - the resolved command
* @param cmdSubSystem - this connection's command subsystem, which will run the command
* @param context - the selected IRemoteFile object
* @return true if we should continue, false if something went wrong
*/
public static boolean runUniversalCommand(Shell shell, String cmdString, IRemoteCmdSubSystem cmdSubSystem, Object context) {
String path = RemoteCommandHelpers.getWorkingDirectory((IRemoteFile) context);
boolean ok = RemoteCommandHelpers.runUniversalCommand(shell, cmdString, path, cmdSubSystem);
return ok;
} // end method
// -----------------------------------------------
// OVERRIDDEN METHODS FOR CAPABILITY DEFINITION
// -----------------------------------------------
/**
* Return true if actions can be scoped by file types
* The iSeries native file system does support types
*/
public boolean supportsTypes() {
return true;
}
/**
* Return true if actions can be scoped by file types for the given domain.
* Default is supportsTypes()
*/
public boolean supportsTypes(int domain) {
if (domain == DOMAIN_FOLDER)
return false;
else
return true;
}
/**
* Return true if the action/type manager supports domains.
* The iSeries native file system does support domains
*/
public boolean supportsDomains() {
return true;
}
/**
* In some cases, we supports domains in general, but only want to expose
* one of those domains to the user. For example, for file subsystems,
* we support folder and file domains, but for named types we really only
* support the file domain.
* <p>
* We return DOMAIN_FILE if the docManager is the type manager
*/
public int getSingleDomain(SystemUDBaseManager docManager) {
if (docManager != getUDTypeManager())
return -1;
else
return DOMAIN_FILE;
}
// --------------------
// VARIOUS OVERRIDES...
// --------------------
/**
* Subclasses may override to provide a custom type edit pane subclass
*/
public SystemUDTypeEditPane getCustomUDTypeEditPane(ISubSystem ss, ISubSystemConfiguration ssf, ISystemProfile profile, ISystemUDAEditPaneHoster parent, ISystemUDTreeView tv) {
return new UDTypesEditPaneFiles(ss, ssf, profile, parent, tv);
}
/**
* Prime new document with default types. This adds all the types that common across all system types,
* but also allows unique types to be added per system by calling primeAdditionalDefaultUniversalTypes,
* which is a method that subclasses can override.
* <p>
* Do no override this method, but instead override primeAdditionalDefaultUniversalTypes.
*/
public SystemUDTypeElement[] primeDefaultTypes(SystemUDTypeManager typeMgr) {
Vector v = new Vector();
primeDefaultUniversalTypes(typeMgr, v);
// give subclasses a chance...
primeAdditionalDefaultUniversalTypes(typeMgr, v);
// convert vector to array
SystemUDTypeElement[] typesArray = new SystemUDTypeElement[v.size()];
for (int idx = 0; idx < typesArray.length; idx++)
typesArray[idx] = (SystemUDTypeElement) v.elementAt(idx);
return typesArray;
}
/**
* Static version of primeDefaultTypes that is called by the iSeries IFS action subsystem.
* @param typeMgr - the manager of the types document to be primed
* @param vectorOfTypes - the vector to populate with types. Can be null, in which case the results are returned as an array
* @return null if given a vector (it is populated), else the array of default types
*/
public static SystemUDTypeElement[] primeDefaultUniversalTypes(SystemUDTypeManager typeMgr, Vector vectorOfTypes) {
Vector v = vectorOfTypes;
if (v == null) v = new Vector();
for (int i = 0; i < IBM_DEFAULT_FOLDERTYPES.length; i++) {
SystemUDTypeElement ft = typeMgr.addType(DOMAIN_FOLDER, IBM_DEFAULT_FOLDERTYPES[i][0]);
if (null == ft) continue;
v.addElement(ft);
ft.setTypes(IBM_DEFAULT_FOLDERTYPES[i][1]);
}
for (int i = 0; i < IBM_DEFAULT_FILETYPES.length; i++) {
SystemUDTypeElement ft = typeMgr.addType(DOMAIN_FILE, IBM_DEFAULT_FILETYPES[i][0]);
if (null == ft) continue;
v.addElement(ft);
ft.setTypes(IBM_DEFAULT_FILETYPES[i][1]);
}
if (vectorOfTypes != null) return null;
// convert vector to array
SystemUDTypeElement[] typesArray = new SystemUDTypeElement[v.size()];
for (int idx = 0; idx < typesArray.length; idx++)
typesArray[idx] = (SystemUDTypeElement) v.elementAt(idx);
return typesArray;
}
/**
* This is an override point for subclasses to add system-specify default types.
* <p>
* To simplify processing, subclasses should add their additional SystemUDTypeElement
* objects to the given vector.
*/
protected void primeAdditionalDefaultUniversalTypes(SystemUDTypeManager typeMgr, Vector vectorOfTypes) {
}
/**
* Prime new document with default action. This adds all the actions that common across all system types,
* but also allows unique actions to be added per system by calling primeAdditionalDefaultUniversalActions,
* which is a method that subclasses can override.
* <p>
* Do no override this method, but instead override primeAdditionalDefaultUniversalActions.
*/
public SystemUDActionElement[] primeDefaultActions(SystemUDActionManager actionMgr, ISystemProfile profile) {
Vector v = new Vector();
primeDefaultUniversalActions(actionMgr, profile, v);
// give subclasses a chance...
primeAdditionalDefaultUniversalActions(actionMgr, profile, v);
// convert vector to array
SystemUDActionElement[] actionArray = new SystemUDActionElement[v.size()];
for (int idx = 0; idx < actionArray.length; idx++)
actionArray[idx] = (SystemUDActionElement) v.elementAt(idx);
return actionArray;
}
/**
* Static version of primeDefaultActions that is called by the iSeries IFS action subsystem.
* @param actionMgr - the manager of the actions document to be primed
* @param vectorOfActions - the vector to populate with actions. Can be null, in which case the results are returned as an array
* @return null if given a vector (it is populated), else the array of default actions
*/
public static SystemUDActionElement[] primeDefaultUniversalActions(SystemUDActionManager actionMgr, ISystemProfile profile, Vector vectorOfActions) {
Vector v = vectorOfActions;
if (v == null) v = new Vector();
// add file actions
int domain = DOMAIN_FILE;
SystemUDActionElement newAction;
for (int idx = 0; idx < FILE_ACTIONS.length; idx++) {
newAction = actionMgr.addAction(profile, FILE_ACTIONS[idx][0], domain);
v.addElement(newAction);
newAction.setCommand(FILE_ACTIONS[idx][5]);
newAction.setPrompt(true); // may as well always allow users chance to change command as its submitted
newAction.setRefresh(FILE_ACTIONS[idx][1].equals("true")); //$NON-NLS-1$
newAction.setShow(true);
newAction.setSingleSelection(FILE_ACTIONS[idx][2].equals("true")); //$NON-NLS-1$
newAction.setCollect(FILE_ACTIONS[idx][3].equals("true")); //$NON-NLS-1$
newAction.setFileTypes(convertStringToArray(FILE_ACTIONS[idx][4]));
}
// add folder actions
domain = DOMAIN_FOLDER;
for (int idx = 0; idx < FOLDER_ACTIONS.length; idx++) {
newAction = actionMgr.addAction(profile, FOLDER_ACTIONS[idx][0], domain);
v.addElement(newAction);
newAction.setCommand(FOLDER_ACTIONS[idx][4]);
newAction.setPrompt(true); // may as well always allow users chance to change command as its submitted
newAction.setRefresh(FOLDER_ACTIONS[idx][1].equals("true")); //$NON-NLS-1$
newAction.setShow(true);
newAction.setSingleSelection(FOLDER_ACTIONS[idx][2].equals("true")); //$NON-NLS-1$
newAction.setCollect(FOLDER_ACTIONS[idx][3].equals("true")); //$NON-NLS-1$
newAction.setFileTypes(new String[] { "ALL" }); //$NON-NLS-1$
}
if (vectorOfActions != null) return null;
// convert vector to array...
SystemUDActionElement[] actionArray = new SystemUDActionElement[v.size()];
for (int idx = 0; idx < actionArray.length; idx++)
actionArray[idx] = (SystemUDActionElement) v.elementAt(idx);
return actionArray;
}
/**
* This is an override point for subclasses to add system-specify default actions.
* <p>
* To simplify processing, subclasses should add their additional SystemUDActionElement
* objects to the given vector.
*/
protected void primeAdditionalDefaultUniversalActions(SystemUDActionManager actionMgr, ISystemProfile profile, Vector vectorOfActions) {
}
/**
* Given this IBM-supplied named type, restore it to its IBM-supplied state
* @return true if all went well, false if it wasn't restore for some reason
*/
public boolean restoreDefaultType(SystemUDTypeElement element, int domain, String typeName) {
boolean ok = restoreUniversalDefaultType(element, domain, typeName);
if (!ok) ok = restoreAdditionalDefaultType(element, domain, typeName);
return ok;
}
/**
* Given this IBM-supplied named type, restore it to its IBM-supplied state.
* This concrete method tests the commonly supplied universal types.
* @return true if all went well, false if it wasn't restore for some reason
*/
public static boolean restoreUniversalDefaultType(SystemUDTypeElement element, int domain, String typeName) {
boolean ok = false;
String[][] typesArray = IBM_DEFAULT_FILETYPES;
if (domain == DOMAIN_FOLDER) // no IBM types for folder.
typesArray = IBM_DEFAULT_FOLDERTYPES;
// first test the universal types...
int match = -1;
for (int idx = 0; (match == -1) && (idx < typesArray.length); idx++) {
if (typeName.equals(typesArray[idx][0])) match = idx;
}
if (match != -1) {
element.setName(typesArray[match][0]);
element.setTypes(typesArray[match][1]);
ok = true;
}
return ok;
}
/**
* Given this IBM-supplied named type, restore it to its IBM-supplied state.
* This abstract method is for the subclasses.
* @return true if all went well, false if it wasn't restore for some reason
*/
protected boolean restoreAdditionalDefaultType(SystemUDTypeElement element, int domain, String typeName) {
return false;
}
/**
* Given this IBM-supplied named action, restore it to its IBM-supplied state
* @return true if all went well, false if it wasn't restore for some reason
*/
public boolean restoreDefaultAction(SystemUDActionElement element, int domain, String typeName) {
boolean ok = restoreUniversalDefaultAction(element, domain, typeName);
if (!ok) ok = restoreAdditionalDefaultAction(element, domain, typeName);
return ok;
}
/**
* Given this IBM-supplied named action, restore it to its IBM-supplied state.
* This concrete method tests the commonly supplied universal actions.
* @return true if all went well, false if it wasn't restore for some reason
*/
public static boolean restoreUniversalDefaultAction(SystemUDActionElement element, int domain, String actionName) {
boolean ok = false;
String[][] actionsArray = FILE_ACTIONS;
if (domain == DOMAIN_FOLDER) // no IBM types for folder.
actionsArray = FOLDER_ACTIONS;
// first test the universal types...
int match = -1;
for (int idx = 0; (match == -1) && (idx < actionsArray.length); idx++) {
if (actionName.equals(actionsArray[idx][0])) match = idx;
}
if (match != -1) {
element.setName(actionsArray[match][0]);
element.setPrompt(true); // may as well always allow users chance to change command as its submitted
element.setRefresh(actionsArray[match][1].equals("true")); //$NON-NLS-1$
element.setShow(true);
element.setSingleSelection(actionsArray[match][2].equals("true")); //$NON-NLS-1$
element.setCollect(actionsArray[match][3].equals("true")); //$NON-NLS-1$
if (domain == DOMAIN_FOLDER)
element.setFileTypes(new String[] { "ALL" }); //$NON-NLS-1$
else
element.setFileTypes(convertStringToArray(actionsArray[match][4]));
element.setCommand(actionsArray[match][5]);
ok = true;
}
return ok;
}
/**
* Given this IBM-supplied named action, restore it to its IBM-supplied state.
* This abstract method is for the subclasses.
* @return true if all went well, false if it wasn't restore for some reason
*/
protected boolean restoreAdditionalDefaultAction(SystemUDActionElement element, int domain, String actionName) {
return false;
}
/**
* Convert space-delimited string into array of strings
*/
protected static String[] convertStringToArray(String string) {
StringTokenizer tokens = new StringTokenizer(string);
Vector v = new Vector();
while (tokens.hasMoreTokens()) {
v.addElement(tokens.nextToken());
}
String[] strings = new String[v.size()];
for (int idx = 0; idx < strings.length; idx++)
strings[idx] = (String) v.elementAt(idx);
return strings;
}
/**
* We disable user defined actions if we are in work-offline mode.
* Currently, how we determine this is dependent on the subsystem factory.
*/
public boolean getWorkingOfflineMode() {
return false; // todo: change this when offline mode is supported for universal!
}
/**
* Return the list of substitution variables for the given domain type.
* Called from edit pane in work with dialog.
* This must be overridden!
*/
public SystemCmdSubstVarList getActionSubstVarList(int actionDomainType) {
if (actionDomainType == DOMAIN_FOLDER)
return UDSubstListFolders.getSingleton();
else if (actionDomainType == DOMAIN_FILE)
return UDSubstListFiles.getSingleton();
else
return null;
}
/**
* Given an action, and the currently selected remote objects, and the domain of those,
* return true if ALL of the selected remote objects matches any of the type criteria
* for this action
* <p>
* Override of parent
*/
protected boolean meetsSelection(SystemUDActionElement action, IStructuredSelection selection, int domainType) {
if (domainType == DOMAIN_FOLDER) return true; // no point in further testing because our getDomainFromSelection method already did this
String unresolvedActionTypes[] = action.getFileTypes();
// fastpath for "ALL"!
if ((unresolvedActionTypes == null) || (unresolvedActionTypes.length == 0))
return true; // what else to do?
else if (unresolvedActionTypes[0].equals("ALL")) //$NON-NLS-1$
return true;
// flatten types
String[] actionTypes = resolveTypes(unresolvedActionTypes, domainType);
// create file type matcher
fileTypeMatcher = null;
if (domainType == DOMAIN_FILE) {
if (fileTypeMatcher == null) fileTypeMatcher = new FileTypeMatcher(null, getSubsystem().getSubSystemConfiguration().isCaseSensitive());
fileTypeMatcher.setTypesAndNames(actionTypes);
}
Iterator elements = selection.iterator();
Object element = null;
while (elements.hasNext()) {
element = elements.next();
IRemoteFile file = (IRemoteFile) element;
// OK if matches any one of the file types for an action
boolean foundMatch = false;
if (domainType == DOMAIN_FOLDER) {
if (file.isDirectory()) foundMatch = true;
} else {
if (fileTypeMatcher.matches(file.getName())) foundMatch = true;
}
if (!foundMatch) return false;
}
return true;
}
/**
* Parent override.
* <p>
* Compares a particular file type (not named, but actual scalar/generic type)
* to a specific user-selected remote object.
* Returns true if the object's information matches that of the given type
* <p>
* BECAUSE WE OVERRRIDE meetsSelection, THIS METHOD IS NEVER CALLED FOR US!
*
* @param actionType - an unnamed file type, as in "*.cpp"
* @param selectedObject - one of the currently selected remote objects
* @param domainType - integer representation of current domain
*/
protected boolean isMatch(Object actionType, Object selectedObject, int domainType) {
return true;
}
// -----------------------------------------------
// OVERRIDDEN METHODS RELATED TO DOMAIN SUPPORT...
// -----------------------------------------------
/**
* Parent override.
* Determine domain, given the selection.
* Eg subsystem that supports domains has to do this via overriding this method.
* If domains not supported, return -1.
*/
protected int getDomainFromSelection(IStructuredSelection selection) {
int domain = -1;
Iterator elements = selection.iterator();
if (elements.hasNext()) {
IRemoteFile currFile = (IRemoteFile) elements.next();
if (currFile.isDirectory())
domain = DOMAIN_FOLDER;
else
domain = DOMAIN_FILE;
}
return domain;
}
/**
* Parent override.
* For efficiency reasons, internally we use an integer to represent a domain.
* However, that has to be mapped to a name which is actually what is stored as the
* "type" attribute for the xml domain node.
* This returns the maximum integer number supported by this action/type manager.
* Returns 1 for us.
*/
public int getMaximumDomain() {
return 1;
}
/**
* Get the list of untranslated domain names
*/
public String[] getDomainNames() {
return DOMAINS;
}
/**
* Get the list of translated domain names
*/
public String[] getXlatedDomainNames() {
return DOMAIN_NAME_STRING;
}
/**
* Get the list of translated domain names for the tree view's "New" nodes
*/
public String[] getXlatedDomainNewNames() {
return DOMAIN_NEWNAME_STRING;
}
/**
* Get the list of translated domain names for "new" nodes in tree view, for the WW Named Types dialog
*/
public String[] getXlatedDomainNewTypeNames() {
return DOMAIN_NEWNAME_STRING;
//return DOMAIN_NEWTYPENAME_STRING; // SHOULD NEVER BE CALLED
}
/**
* Get the domain icon to show in the tree views
*/
public Image getDomainImage(int domain) {
if (domain == DOMAIN_FOLDER)
return RSEUIPlugin.getDefault().getImage(ISystemIconConstants.ICON_SYSTEM_FOLDER_ID);
//return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
else if (domain == DOMAIN_FILE)
//return RSEUIPlugin.getDefault().getImage(ISystemConstants.ICON_SYSTEM_FILE_ID);
return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
return null;
}
/**
* Get the domain icon to show in the tree views, for the new item for this domain
*/
public Image getDomainNewImage(int domain) {
if (domain == DOMAIN_FOLDER)
return RSEUIPlugin.getDefault().getImage(ISystemIconConstants.ICON_SYSTEM_NEWFOLDER_ID);
//return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
else if (domain == DOMAIN_FILE) return RSEUIPlugin.getDefault().getImage(ISystemIconConstants.ICON_SYSTEM_NEWFILE_ID);
//return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
return null;
}
/**
* Get the domain icon to show in the named type tree view, for the new item for this domain
*/
public Image getDomainNewTypeImage(int domain) {
return UserActionsIcon.USERTYPE_NEW.getImage();
}
/**
* Overridable method for child classes to supply the label to display in the
* "New" node for types. Typically only overriden if domains are not supported, as otherwise
* the child nodes of "New" have the specific labels.
* @return translated label for "New named type..."
*/
protected String getNewNodeTypeLabel() {
return SystemUDAResources.RESID_UDA_FILES_NEWNODE_LABEL;
}
}

View file

@ -0,0 +1,114 @@
package org.eclipse.rse.useractions.files.uda;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.Vector;
import org.eclipse.rse.core.model.ISystemProfile;
import org.eclipse.rse.useractions.ui.uda.SystemUDActionElement;
import org.eclipse.rse.useractions.ui.uda.SystemUDActionManager;
import org.eclipse.rse.useractions.ui.uda.SystemUDTypeElement;
import org.eclipse.rse.useractions.ui.uda.SystemUDTypeManager;
/**
* This is a specialization of the universal files user action support, for
* stuff unique to Local files.
*/
public class UDActionSubsystemLocalFiles extends UDActionSubsystemFiles {
/**
* Constructor for UDActionSubsystemLocalFiles.
*/
public UDActionSubsystemLocalFiles() {
super();
}
/**
* Parent intercept for adding default pre-defined types that are unique to us.
*/
protected void primeAdditionalDefaultUniversalTypes(SystemUDTypeManager typeMgr, Vector vectorOfTypes) {
// I have decided not to include the iSeries unique types as there are user actions I can imagine for them,
// and they clutter up the namespace for non-iSeries users...
/*
// the following contains ONLY those types that are unique to local.
// for now these are only local copies of remote iSeries members
final String fileTypes[][] =
{
{"CBL_400", "cbl,cblle,lbl,sqlcblle" },
{"CL_400", "clp,clle,cmd400,icl" },
{"DDS_400", "dds,dspf,prtf,pf,lf,icff" },
{"RPG_400", "rpg,rpgle,rpt" },
};
for (int i = 0; i < fileTypes.length; i++)
{
SystemUDTypeElement ft = typeMgr.addType(DOMAIN_FILE, fileTypes[i][0]);
if (null == ft)
continue;
vectorOfTypes.addElement(ft);
ft.setTypes(fileTypes[i][1]);
}
*/
}
/**
* Parent intercept for adding default pre-defined actions that are unique to us.
*/
protected void primeAdditionalDefaultUniversalActions(SystemUDActionManager actionMgr, ISystemProfile profile, Vector vectorOfActions) {
// duplicate the non-iseries types...
int domain = DOMAIN_FILE;
SystemUDActionElement newAction;
for (int idx = 0; idx < UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS.length; idx++) {
newAction = actionMgr.addAction(profile, UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[idx][0], domain);
vectorOfActions.addElement(newAction);
newAction.setCommand(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[idx][5]);
newAction.setPrompt(true); // may as well always allow users chance to change command as its submitted
newAction.setRefresh(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[idx][1].equals("true")); //$NON-NLS-1$
newAction.setShow(true);
newAction.setSingleSelection(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[idx][2].equals("true")); //$NON-NLS-1$
newAction.setCollect(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[idx][3].equals("true")); //$NON-NLS-1$
newAction.setFileTypes(convertStringToArray(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[idx][4]));
}
// add actions unique to local...
}
/**
* Parent intercept for restoring one of our unique IBM-supplied actions to its original state.
* @return true if all went well, false if it wasn't restore for some reason
*/
protected boolean restoreAdditionalDefaultAction(SystemUDActionElement element, int domain, String actionName) {
boolean ok = false;
if (domain == DOMAIN_FOLDER) return ok;
int match = -1;
for (int idx = 0; (match == -1) && (idx < UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS.length); idx++) {
if (UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[idx][0].equals(actionName)) match = idx;
}
if (match != -1) {
element.setName(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[match][0]);
element.setPrompt(true); // may as well always allow users chance to change command as its submitted
element.setRefresh(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[match][1].equals("true")); //$NON-NLS-1$
element.setShow(true);
element.setSingleSelection(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[match][2].equals("true")); //$NON-NLS-1$
element.setCollect(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[match][3].equals("true")); //$NON-NLS-1$
element.setFileTypes(convertStringToArray(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[match][4]));
element.setCommand(UDActionSubsystemUniversalFiles.UNIVERSAL_FILE_ACTIONS[match][5]);
ok = true;
}
return ok;
}
/**
* Override of parent method to restore unique type supplied by us, to its original state.
* @return true if all went well, false if it wasn't restore for some reason
*/
protected boolean restoreAdditionalDefaultType(SystemUDTypeElement element, int domain, String typeName) {
return false; // nothing unique
}
}

View file

@ -0,0 +1,113 @@
package org.eclipse.rse.useractions.files.uda;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.Vector;
import org.eclipse.rse.core.model.ISystemProfile;
import org.eclipse.rse.useractions.ui.uda.SystemUDActionElement;
import org.eclipse.rse.useractions.ui.uda.SystemUDActionManager;
import org.eclipse.rse.useractions.ui.uda.SystemUDTypeElement;
import org.eclipse.rse.useractions.ui.uda.SystemUDTypeManager;
/**
* This is a specialization of the universal files user action support, for
* stuff unique to non-Local, non-IFS files.
*/
public class UDActionSubsystemUniversalFiles extends UDActionSubsystemFiles {
/**
* Universal non-iseries actions
*/
protected static final String UNIVERSAL_FILE_ACTIONS[][] =
// name, refresh, singleSel, collect, types, cmd
{
// these probably should be deleted, as these are more appropriate as compile commands
// {"gcc", "true", "false", "false", "CPP_COMPILABLE C_COMPILABLE","gcc -c ${resource_name} -o ${resource_name_root}.o"},
// {"cc", "true", "false", "false", "CPP_COMPILABLE C_COMPILABLE","cc -c ${resource_name} -o ${resource_name_root}.o"},
//{"IBM C", "true", "false", "false", "C_COMPILABLE", "xlc -c -qinfo=all ${resource_name} -o ${resource_name_root}.o"},
//{"IBM C++","true", "false", "false", "CPP_COMPILABLE", "xlC -c -qinfo=all ${resource_name} -o ${resource_name_root}.o"},
};
/**
* Constructor
*/
public UDActionSubsystemUniversalFiles() {
super();
}
/**
* Parent intercept for adding default pre-defined types that are unique to us.
*/
protected void primeAdditionalDefaultUniversalTypes(SystemUDTypeManager typeMgr, Vector vectorOfTypes) {
return; // nothing unique
}
/**
* Parent intercept for adding default pre-defined actions that are unique to us.
*/
protected void primeAdditionalDefaultUniversalActions(SystemUDActionManager actionMgr, ISystemProfile profile, Vector vectorOfActions) {
// add file actions
int domain = DOMAIN_FILE;
SystemUDActionElement newAction;
for (int idx = 0; idx < UNIVERSAL_FILE_ACTIONS.length; idx++) {
newAction = actionMgr.addAction(profile, UNIVERSAL_FILE_ACTIONS[idx][0], domain);
vectorOfActions.addElement(newAction);
newAction.setCommand(UNIVERSAL_FILE_ACTIONS[idx][5]);
newAction.setPrompt(true); // may as well always allow users chance to change command as its submitted
newAction.setRefresh(UNIVERSAL_FILE_ACTIONS[idx][1].equals("true")); //$NON-NLS-1$
newAction.setShow(true);
newAction.setSingleSelection(UNIVERSAL_FILE_ACTIONS[idx][2].equals("true")); //$NON-NLS-1$
newAction.setCollect(UNIVERSAL_FILE_ACTIONS[idx][3].equals("true")); //$NON-NLS-1$
newAction.setFileTypes(convertStringToArray(UNIVERSAL_FILE_ACTIONS[idx][4]));
}
}
/**
* We disable user defined actions if we are in work-offline mode.
* Currently, how we determine this is dependent on the subsystem factory.
*/
public boolean getWorkingOfflineMode() {
return false; // todo... set to preferences setting when offline mode supported for universal
}
/**
* Parent intercept for restoring one of our unique IBM-supplied actions to its original state.
* @return true if all went well, false if it wasn't restore for some reason
*/
protected boolean restoreAdditionalDefaultAction(SystemUDActionElement element, int domain, String actionName) {
boolean ok = false;
if (domain == DOMAIN_FOLDER) return ok;
int match = -1;
for (int idx = 0; (match == -1) && (idx < UNIVERSAL_FILE_ACTIONS.length); idx++) {
if (UNIVERSAL_FILE_ACTIONS[idx][0].equals(actionName)) match = idx;
}
if (match != -1) {
element.setName(UNIVERSAL_FILE_ACTIONS[match][0]);
element.setPrompt(true); // may as well always allow users chance to change command as its submitted
element.setRefresh(UNIVERSAL_FILE_ACTIONS[match][1].equals("true")); //$NON-NLS-1$
element.setShow(true);
element.setSingleSelection(UNIVERSAL_FILE_ACTIONS[match][2].equals("true")); //$NON-NLS-1$
element.setCollect(UNIVERSAL_FILE_ACTIONS[match][3].equals("true")); //$NON-NLS-1$
element.setFileTypes(convertStringToArray(UNIVERSAL_FILE_ACTIONS[match][4]));
element.setCommand(UNIVERSAL_FILE_ACTIONS[match][5]);
ok = true;
}
return ok;
}
/**
* Override of parent method to restore unique type supplied by us, to its original state.
* @return true if all went well, false if it wasn't restore for some reason
*/
protected boolean restoreAdditionalDefaultType(SystemUDTypeElement element, int domain, String typeName) {
return false; // nothing unique
}
}

View file

@ -0,0 +1,59 @@
package org.eclipse.rse.useractions.files.uda;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.rse.useractions.ui.SystemCmdSubstVarList;
import org.eclipse.rse.useractions.ui.uda.SystemUDAResources;
import org.eclipse.rse.useractions.ui.uda.SystemUDASubstVarListCommon;
/**
* Encapsulation of the common substitution variables for both folders and files.
* Superset of overall system common variables.
*/
public class UDSubstListCommonFiles extends SystemCmdSubstVarList {
/* from resource property file...
...uda.files.subvar.resource_date = Last modified date of selected resource
...uda.files.subvar.resource_name = Name of selected resource, unqualified
...uda.files.subvar.resource_path = Path of selected resource, including name
...uda.files.subvar.resource_path_root=Root of selected file's path. "c:\\" on Windows, or "/" on others
...uda.files.subvar.resource_path_drive=Drive letter on Windows, empty string on others
...uda.files.subvar.container_name=Name of folder containing selected resource, unqualified
...uda.files.subvar.container_path=Path of folder containing selected resource, including name
*/
private static final String[] COMMON_VARNAMES = { "resource_date", //$NON-NLS-1$
"resource_name", //$NON-NLS-1$
"resource_path", //$NON-NLS-1$
"resource_path_root", //$NON-NLS-1$
"resource_path_drive", //$NON-NLS-1$
"container_name", //$NON-NLS-1$
"container_path" //$NON-NLS-1$
};
private static final String[] COMMON_DESCRIPTIONS = { SystemUDAResources.RESID_UDA_FILES_SUBVAR_RESOURCE_DATE, SystemUDAResources.RESID_UDA_FILES_SUBVAR_RESOURCE_NAME,
SystemUDAResources.RESID_UDA_FILES_SUBVAR_RESOURCE_PATH, SystemUDAResources.RESID_UDA_FILES_SUBVAR_RESOURCE_PATH_ROOT, SystemUDAResources.RESID_UDA_FILES_SUBVAR_RESOURCE_PATH_DRIVE,
SystemUDAResources.RESID_UDA_FILES_SUBVAR_CONTAINER_NAME, SystemUDAResources.RESID_UDA_FILES_SUBVAR_CONTAINER_PATH };
private static UDSubstListCommonFiles inst = null;
/**
* Constructor .
* Not to be used directly. Rather, use getSingleton().
*/
UDSubstListCommonFiles() {
super(SystemUDASubstVarListCommon.getSingleton(), COMMON_VARNAMES, COMMON_DESCRIPTIONS);
}
/**
* Return the singleton of this object. No need ever for more than one instance
*/
public static UDSubstListCommonFiles getSingleton() {
if (inst == null) inst = new UDSubstListCommonFiles();
return inst;
}
}

View file

@ -0,0 +1,48 @@
package org.eclipse.rse.useractions.files.uda;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.rse.useractions.ui.SystemCmdSubstVarList;
import org.eclipse.rse.useractions.ui.uda.SystemUDAResources;
/**
* @author coulthar
*
* Substitution variables for folders. Superset of common list
*/
public class UDSubstListFiles extends SystemCmdSubstVarList {
/* from resource property file...
...uda.files.subvar.resource_name_root=Name of selected resource without the extension
...uda.files.subvar.resource_name_ext=Extension part of the name of the selected resource
*/
private static final String[] FILE_VARNAMES = { "resource_name_ext", //$NON-NLS-1$
"resource_name_root" //$NON-NLS-1$
};
private static final String[] DESCRIPTIONS = { SystemUDAResources.RESID_UDA_FILES_SUBVAR_RESOURCE_NAME_EXT, SystemUDAResources.RESID_UDA_FILES_SUBVAR_RESOURCE_NAME_ROOT };
private static UDSubstListFiles inst = null;
/**
* Constructor .
* Not to be used directly. Rather, use getSingleton().
*/
UDSubstListFiles() {
super(UDSubstListCommonFiles.getSingleton(), FILE_VARNAMES, DESCRIPTIONS);
testForDuplicates();
}
/**
* Return the singleton of this object. No need ever for more than one instance
*/
public static UDSubstListFiles getSingleton() {
if (inst == null) inst = new UDSubstListFiles();
return inst;
}
}

View file

@ -0,0 +1,41 @@
package org.eclipse.rse.useractions.files.uda;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.rse.useractions.ui.SystemCmdSubstVarList;
/**
* @author coulthar
*
* Substitution variables for folders. Superset of common list
*/
public class UDSubstListFolders extends SystemCmdSubstVarList {
private static final String[] FOLDER_VARNAMES = {};
private static final String[] DESCRIPTIONS = {};
private static UDSubstListFolders inst = null;
/**
* Constructor .
* Not to be used directly. Rather, use getSingleton().
*/
UDSubstListFolders() {
super(UDSubstListCommonFiles.getSingleton(), FOLDER_VARNAMES, DESCRIPTIONS);
testForDuplicates();
}
/**
* Return the singleton of this object. No need ever for more than one instance
*/
public static UDSubstListFolders getSingleton() {
if (inst == null) inst = new UDSubstListFolders();
return inst;
}
}

View file

@ -0,0 +1,71 @@
package org.eclipse.rse.useractions.files.uda;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import org.eclipse.rse.core.model.ISystemProfile;
import org.eclipse.rse.core.subsystems.ISubSystem;
import org.eclipse.rse.core.subsystems.ISubSystemConfiguration;
import org.eclipse.rse.useractions.ui.uda.ISystemUDAEditPaneHoster;
import org.eclipse.rse.useractions.ui.uda.ISystemUDTreeView;
import org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector;
import org.eclipse.rse.useractions.ui.uda.SystemUDTypeEditPane;
import org.eclipse.swt.widgets.Composite;
/**
* @author coulthar
*
* This is a refinement of the generic edit pane for defining
* new named file types, specifialized for universal files.
* Specifically, it overrides the editor used to select/specify
* the individual types that constitute the named type.
*/
public class UDTypesEditPaneFiles extends SystemUDTypeEditPane {
/**
* Constructor for UDTypesEditPaneFiles.
* @param ss
* @param parent
* @param tv
*/
public UDTypesEditPaneFiles(ISubSystem ss, ISubSystemConfiguration ssf, ISystemProfile profile, ISystemUDAEditPaneHoster parent, ISystemUDTreeView tv) {
super(ss, ssf, profile, parent, tv);
}
/**
* Overridable exit point.
* Return true if the types are to be auto-uppercased.
* We return false
*/
protected boolean getAutoUpperCaseTypes() {
return false;
}
/**
* Overridable exit point from parent.
* Create the edit widgets that will allow the user to see and
* edit the list of file types that constitute this named type.
* <p>
* To better facilitate this, the only requirement is that this
* "editor" meet the minimal interface
* {@link org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector}
* <p>
* Our implementation is to return an instance of our custom UDDTypesEditorFiles class.
*
* @param parent - the parent composite where the widgets are to go
* @param nbrColumns - the number of columns in the parent composite, which these
* widgets should span
* @return a class implementing the required interface
*/
protected ISystemUDTypeEditPaneTypesSelector createTypesListEditor(Composite parent, int nbrColumns) {
UDTypesEditorFiles ourEditor = new UDTypesEditorFiles(parent, nbrColumns);
//ourEditor.setAutoUpperCase(getAutoUpperCaseTypes());
return ourEditor;
}
}

View file

@ -0,0 +1,567 @@
package org.eclipse.rse.useractions.files.uda;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.rse.services.clientserver.messages.SystemMessage;
import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString;
import org.eclipse.rse.ui.ISystemIconConstants;
import org.eclipse.rse.ui.ISystemMessages;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.ui.SystemWidgetHelpers;
import org.eclipse.rse.ui.messages.ISystemMessageLine;
import org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector;
import org.eclipse.rse.useractions.ui.uda.SystemUDAResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IFileEditorMapping;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.FileEditorMappingContentProvider;
import org.eclipse.ui.dialogs.FileEditorMappingLabelProvider;
/**
* This class implements the interface needed to supply
* custom widgets allowing the user to specify the file types
* for a named file type, in the Work With File Types dialog
*/
public class UDTypesEditorFiles implements ISystemUDTypeEditPaneTypesSelector, ISystemIconConstants, ICheckStateListener {
public static final String NO_EXTENSION_PLACEHOLDER = UDActionSubsystemFiles.NO_EXTENSION_PLACEHOLDER;
// gui widgets
private CheckboxTableViewer typesSelectionList;
//private Label typesSelectionListVerbage;
//private Button addTypesButton;
//private Text definedTypesText;
private Label definedTypesLabel;
private Text userDefinedText;
private Label nonEditableVerbage;
private Composite typesComposite;
// state
private java.util.List inpTypes;
private IFileEditorMapping[] currentInput;
private int currentDomain;
private boolean ignoreModifyEvents = false;
// constants
private static final int LIST_HEIGHT = 150;
private static final int LIST_WIDTH = 50;
private static final String TYPE_DELIMITER = ","; //GenericMessages.getString("TypesFiltering.typeDelimiter"); //$NON-NLS-1$
// registered listeners
private Vector listeners = new Vector();
/**
* Constructor for UDTypesEditorFiles.
*/
public UDTypesEditorFiles(Composite comp, int nbrColumns) //, SystemPromptDialog parentDialog)
{
super();
// List of currently selected types if given parent composite has 2 columns
if (nbrColumns == 2) {
//definedTypesText =
// SystemWidgetHelpers.createLabeledTextField(comp, null, rb, RESID_UDT_FILES_DEFINEDTYPES_ROOT);
definedTypesLabel = SystemWidgetHelpers.createLabeledLabel(comp, SystemUDAResources.RESID_UDT_FILES_DEFINEDTYPES_LABEL, SystemUDAResources.RESID_UDT_FILES_DEFINEDTYPES_TOOLTIP, true);
}
nonEditableVerbage = SystemWidgetHelpers.createVerbiage(comp, "", nbrColumns, false, 350); //$NON-NLS-1$
nonEditableVerbage.setVisible(false);
//typesComposite = SystemWidgetHelpers.createGroupComposite(comp, 1, rb.getString(RESID_UDT_FILES_TYPESGROUP_ROOT_LABEL);
typesComposite = SystemWidgetHelpers.createTightComposite(comp, 1);
typesComposite.setToolTipText(SystemUDAResources.RESID_UDT_FILES_TYPESGROUP_TOOLTIP);
((GridData) typesComposite.getLayoutData()).horizontalSpan = nbrColumns;
nbrColumns = 1;
// List of currently selected types if given parent composite did not have 2 columns
if (definedTypesLabel == null)
//definedTypesText =
// SystemWidgetHelpers.createLabeledTextField(typesComposite, null, rb, RESID_UDT_FILES_DEFINEDTYPES_ROOT);
definedTypesLabel = SystemWidgetHelpers.createLabeledLabel(typesComposite, SystemUDAResources.RESID_UDT_FILES_DEFINEDTYPES_LABEL, SystemUDAResources.RESID_UDT_FILES_DEFINEDTYPES_TOOLTIP,
true);
//definedTypesLabel.setEnabled(false);
definedTypesLabel.setForeground(definedTypesLabel.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
//definedTypesText =
// SystemWidgetHelpers.createReadonlyTextField(typesComposite, rb, RESID_UDT_FILES_DEFINEDTYPES_ROOT);
//definedTypesText.setToolTipText("");
//definedTypesText.setVisible(false);
// types selection label
//typesSelectionListVerbage =
// SystemWidgetHelpers.createLabel(typesComposite, rb, RESID_UDT_TYPESLIST_LABEL_ROOT, nbrColumns, false);
// types selection list
//typesSelectionList = CheckboxTableViewer.newCheckList(comp, SWT.BORDER);
Table table = new Table(typesComposite, SWT.CHECK | SWT.BORDER);
table.setToolTipText(SystemUDAResources.RESID_UDT_FILES_TYPESGROUP_TOOLTIP);
typesSelectionList = new CheckboxTableViewer(table);
GridData data = new GridData(GridData.FILL_BOTH);
data.horizontalSpan = nbrColumns;
data.heightHint = LIST_HEIGHT;
data.widthHint = LIST_WIDTH;
//data.grabExcessHorizontalSpace = false;
//data.grabExcessVerticalSpace = false;
typesSelectionList.getTable().setLayoutData(data);
typesSelectionList.setLabelProvider(FileEditorMappingLabelProvider.INSTANCE);
typesSelectionList.setContentProvider(FileEditorMappingContentProvider.INSTANCE);
addSelectionButtons(typesComposite);
Composite userComp = createUserEntryGroup(typesComposite);
((GridData) userComp.getLayoutData()).horizontalSpan = nbrColumns;
// configure widgets...
initializeViewer();
//if ((this.initialSelections != null) && !this.initialSelections.isEmpty())
// checkInitialSelections();
typesSelectionList.addCheckStateListener(this);
}
/**
* Set domain.
* The edit pane may possibly appear differently, depending on the domain.
* When the domain changes (either in "new" or "edit" mode) this method is called.
*/
public void setDomain(int domain) {
this.currentDomain = domain;
}
/**
* Set the message line for issuing msgs to
*/
public void setMessageLine(ISystemMessageLine msgLine) {
}
/**
* Return the domain of the currently selected existing named type, or "new" node
*/
public int getDomain() {
return currentDomain;
}
/**
* @see org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector#setTypes(String)
*/
public void setTypes(String types) {
//this.inpTypes = types;
if (types == null) {
setTypes((String[]) null);
} else {
setTypes(RemoteFileFilterString.parseTypes(types));
setDefinedTypesText(types);
}
}
/**
* Set defined types text
*/
private void setDefinedTypesText(String types) {
definedTypesLabel.setText(" " + types); //$NON-NLS-1$
definedTypesLabel.setToolTipText(types);
//definedTypesText.setText(types);
}
/**
* Clear defined types text
*/
private void clearDefinedTypesText() {
definedTypesLabel.setText(""); //$NON-NLS-1$
definedTypesLabel.setToolTipText(""); //$NON-NLS-1$
//definedTypesText.setText("");
}
/**
* Set the types via an array
*/
private void setTypes(String[] types) {
clearTypes();
if (types != null) {
this.inpTypes = Arrays.asList(types);
ignoreModifyEvents = true;
checkInitialSelections();
ignoreModifyEvents = false;
}
}
/**
* @see org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector#clearTypes()
*/
public void clearTypes() {
ignoreModifyEvents = true;
this.inpTypes = null;
typesSelectionList.setAllChecked(false);
clearDefinedTypesText();
userDefinedText.setText(""); //$NON-NLS-1$
ignoreModifyEvents = false;
}
/**
* @see org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector#getTypes()
*/
public String getTypes() {
return RemoteFileFilterString.getTypesString(getTypesAsArray());
}
/**
* @see org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector#getTypes()
*/
public String[] getTypesAsArray() {
java.util.List selectedEntries = getSelectedTypes();
String[] seldArray = new String[selectedEntries.size()];
for (int idx = 0; idx < seldArray.length; idx++)
seldArray[idx] = (String) selectedEntries.get(idx);
return seldArray;
}
/**
* @see org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector#addModifyListener(ModifyListener)
*/
public void addModifyListener(ModifyListener listener) {
listeners.add(listener);
}
/**
* @see org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector#removeModifyListener(ModifyListener)
*/
public void removeModifyListener(ModifyListener listener) {
listeners.remove(listener);
}
/**
* @see org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector#validate()
*/
public SystemMessage validate() {
if (typesSelectionList == null) return null;
if (!areTypesSelected()) return RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_VALIDATE_UDTTYPES_EMPTY);
// validate that user-defined entry field!
return validateUserDefinedTypes();
}
/**
* Validate the contents of the user-defined types entry field
*/
public SystemMessage validateUserDefinedTypes() {
String filename = userDefinedText.getText().trim();
// copied from SystemSelectFileTypes...
// check for empty name and extension
if (filename.length() == 0) return null;
// check for empty extension if there is no name
int index = filename.indexOf('.');
if (index == filename.length() - 1) {
if (index == 0 || (index == 1 && filename.charAt(0) == '*')) {
//setErrorMessage(GenericMessages.getString("FileExtension.extensionEmptyMessage")); //$NON-NLS-1$
return RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_VALIDATE_UDTTYPES_NOTVALID);
}
}
int startScan = 0;
if (filename.startsWith("*.")) //$NON-NLS-1$
startScan = 2;
// check for characters before *
// or no other characters
// or next character not '.'
index = filename.indexOf('*', startScan);
if (index > -1) {
if (filename.length() == 1) {
//setErrorMessage(GenericMessages.getString("FileExtension.extensionEmptyMessage")); //$NON-NLS-1$
return RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_VALIDATE_UDTTYPES_NOTVALID);
}
if (index != 0 || filename.charAt(1) != '.') {
//setErrorMessage(GenericMessages.getString("FileExtension.fileNameInvalidMessage")); //$NON-NLS-1$
return RSEUIPlugin.getPluginMessage(ISystemMessages.MSG_VALIDATE_UDTTYPES_NOTVALID);
}
}
return null;
}
/**
* @see org.eclipse.rse.useractions.ui.uda.ISystemUDTypeEditPaneTypesSelector#getControl()
*/
public Control getControl() {
return typesSelectionList.getControl();
}
/**
* Enable or disable the input-capability of the constituent controls
*/
public void setEnabled(boolean enable) {
typesSelectionList.getControl().setEnabled(enable);
userDefinedText.setEnabled(enable);
}
/**
* We want to disable editing of IBM or vendor-supplied
* types, so when one of these is selected, this method is
* called to enter non-editable mode.
* @param editable Whether to disable editing of this type or not
* @param vendor When disabling, it contains the name of the vendor for substitution purposes
*/
public void setEditable(boolean editable, String vendor) {
//setEnabled(editable);
typesComposite.setVisible(editable);
if (editable)
nonEditableVerbage.setVisible(false);
else {
nonEditableVerbage.setVisible(true);
if (vendor.equals("IBM")) //$NON-NLS-1$
nonEditableVerbage.setText(SystemUDAResources.RESID_UDT_IBM_VERBAGE);
else {
String verbage = SystemUDAResources.RESID_UDT_VENDOR_VERBAGE;
verbage = SystemMessage.sub(verbage, "%1", vendor); //$NON-NLS-1$
nonEditableVerbage.setText(verbage);
}
}
}
// private methods...
/**
* Fire event to all listeners...
*/
private void fireModifiedEvent() {
Event event = new Event();
event.widget = getControl();
event.type = SWT.Modify;
event.data = this;
ModifyEvent mEvent = new ModifyEvent(event);
for (int idx = 0; idx < listeners.size(); idx++) {
ModifyListener l = (ModifyListener) listeners.elementAt(idx);
//System.out.println("...firing modify event");
l.modifyText(mEvent);
}
setDefinedTypesText(getTypes());
}
/**
* From ICheckStateListener interface.
* Called when user checks/unchecks an item
*/
public void checkStateChanged(CheckStateChangedEvent event) {
//System.out.println("inside checkStateChanged");
if (!ignoreModifyEvents) fireModifiedEvent();
ignoreModifyEvents = false; // non-sticky
}
// --------------------------------------------
// Similar to org.eclipse.ui.dialogs.TypeFilteringDialog
// --------------------------------------------
/**
* Add the selection and deselection buttons to the dialog.
* @param composite org.eclipse.swt.widgets.Composite
*/
private void addSelectionButtons(Composite composite) {
/*
Composite buttonComposite = new Composite(composite, SWT.RIGHT);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
buttonComposite.setLayout(layout);
GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL);
data.grabExcessHorizontalSpace = true;
composite.setData(data);
Button selectButton = createButton(buttonComposite, IDialogConstants.SELECT_ALL_ID, GenericMessages.getString("WizardTransferPage.selectAll"), false); //$NON-NLS-1$
SelectionListener listener = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e) {
typesSelectionList.setAllChecked(true);
}
};
selectButton.addSelectionListener(listener);
Button deselectButton = createButton(buttonComposite, IDialogConstants.DESELECT_ALL_ID, GenericMessages.getString("WizardTransferPage.deselectAll"), false); //$NON-NLS-1$
listener = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e) {
typesSelectionList.setAllChecked(false);
}
};
deselectButton.addSelectionListener(listener);
*/
}
protected static Button createPushButton(Composite group, String label, String tooltip) {
Button button = createPushButton(group, label);
button.setToolTipText(tooltip);
return button;
}
public static Button createPushButton(Composite group, String label) {
Button button = new Button(group, SWT.PUSH);
button.setText(label);
//button.setText("THIS IS A LONG LABEL. I MEAN, IT IS JUST HUGE!");
GridData data = new GridData(GridData.FILL_HORIZONTAL);
button.setLayoutData(data);
return button;
}
/**
* Add the currently-specified extensions.
*/
private void addUserDefinedEntries(java.util.List result) {
StringTokenizer tokenizer = new StringTokenizer(userDefinedText.getText(), TYPE_DELIMITER);
//Allow the *. and . prefix and extract the extension
while (tokenizer.hasMoreTokens()) {
String currentExtension = tokenizer.nextToken().trim();
if (!currentExtension.equals("")) //$NON-NLS-1$
{
if (currentExtension.startsWith("*."))//$NON-NLS-1$
result.add(currentExtension.substring(2));
else {
if (currentExtension.startsWith("."))//$NON-NLS-1$
result.add(currentExtension.substring(1));
else
result.add(currentExtension);
}
}
}
}
/**
* Visually checks the previously-specified elements in this dialog's list viewer.
*/
private void checkInitialSelections() {
if ((inpTypes == null) || (inpTypes.size() == 0)) return;
IFileEditorMapping editorMappings[] = PlatformUI.getWorkbench().getEditorRegistry().getFileEditorMappings();
ArrayList selectedMappings = new ArrayList();
for (int i = 0; i < editorMappings.length; i++) {
IFileEditorMapping mapping = editorMappings[i];
if (inpTypes.contains(mapping.getLabel())) {
typesSelectionList.setChecked(mapping, true);
selectedMappings.add(mapping.getLabel());
} else {
//System.out.println("name = '" + mapping.getName() + "', label = '" + mapping.getLabel() + "', ext = '" + mapping.getExtension() + "'");
if (mapping.getName().equals("*")) //$NON-NLS-1$
{
if (inpTypes.contains(mapping.getExtension())) {
typesSelectionList.setChecked(mapping, true);
selectedMappings.add(mapping.getExtension());
}
} else if (mapping.getExtension().equals("")) // extension-less name like "makefile" //$NON-NLS-1$
{
if (inpTypes.contains(mapping.getName() + NO_EXTENSION_PLACEHOLDER)) {
typesSelectionList.setChecked(mapping, true);
selectedMappings.add(mapping.getName() + NO_EXTENSION_PLACEHOLDER);
}
}
}
}
//Now add in the ones not selected to the user defined list
Iterator initialIterator = inpTypes.iterator();
StringBuffer entries = new StringBuffer();
while (initialIterator.hasNext()) {
String nextExtension = (String) initialIterator.next();
if (!selectedMappings.contains(nextExtension)) {
entries.append(nextExtension);
entries.append(',');
}
}
this.userDefinedText.setText(entries.toString());
}
/**
* Create the group that shows the user defined entries for the dialog.
* @param parent the parent this is being created in.
*/
private Composite createUserEntryGroup(Composite parent) {
// destination specification group
int nbrColumns = 2;
Composite composite = SystemWidgetHelpers.createFlushComposite(parent, nbrColumns);
userDefinedText = SystemWidgetHelpers.createLabeledTextField(composite, null, SystemUDAResources.RESID_UDT_FILES_USERTYPES_LABEL, SystemUDAResources.RESID_UDT_FILES_USERTYPES_TOOLTIP);
userDefinedText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
if (!ignoreModifyEvents) fireModifiedEvent();
ignoreModifyEvents = false; // non-sticky flag
}
});
SystemWidgetHelpers.setHelp(userDefinedText, RSEUIPlugin.HELPPREFIX + "wwnt0002"); //$NON-NLS-1$
return composite;
}
/**
* Return the input to the dialog.
*/
private IFileEditorMapping[] getInput() {
//Filter the mappings to be just those with a wildcard extension
// Hmm, why does Eclipse do this? Phil
if (currentInput == null) {
currentInput =
//IFileEditorMapping [] allMappings =
PlatformUI.getWorkbench().getEditorRegistry().getFileEditorMappings();
//java.util.List wildcardEditors = new ArrayList();
//for (int i = 0; i < allMappings.length; i++)
//{
//if (allMappings[i].getName().equals("*"))//$NON-NLS-1$
//wildcardEditors.add(allMappings[i]);
//}
//currentInput = new IFileEditorMapping[wildcardEditors.size()];
//wildcardEditors.toArray(currentInput);
}
return currentInput;
}
/**
* Initializes this dialog's viewer after it has been laid out.
*/
private void initializeViewer() {
typesSelectionList.setInput(getInput());
}
/**
* Return the currently selected items as a java.util.List of Strings
*/
protected java.util.List getSelectedTypes() {
// Get the input children.
IFileEditorMapping[] children = getInput();
java.util.List list = new ArrayList();
// Build a list of selected children.
for (int i = 0; i < children.length; ++i) {
IFileEditorMapping element = children[i];
if (typesSelectionList.getChecked(element)) {
if (element.getName().equals("*")) //$NON-NLS-1$
list.add(element.getExtension());
else if (element.getExtension().equals("")) //$NON-NLS-1$
list.add(element.getName() + NO_EXTENSION_PLACEHOLDER);
else
list.add(element.getLabel());
}
}
addUserDefinedEntries(list);
//setResult(list);
return list;
}
/**
* Return true if there are any types currently selected
*/
protected boolean areTypesSelected() {
// Get the input children.
IFileEditorMapping[] children = getInput();
// Test list of selected children.
for (int i = 0; i < children.length; ++i) {
IFileEditorMapping element = children[i];
if (typesSelectionList.getChecked(element)) {
return true;
}
}
String udtText = userDefinedText.getText().trim();
if (udtText.length() == 0) return false;
//StringTokenizer tokenizer =
// new StringTokenizer(udtText, TYPE_DELIMITER);
//return tokenizer.hasMoreTokens();
return true;
}
}

View file

@ -0,0 +1,32 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.rse.useractions.ui;
import org.eclipse.swt.widgets.Composite;
/**
* Interface that is to be implemented by anyone interested in
* supplying additional gui, beyond the default, to the command text widget.
*/
public interface ISystemCommandTextAdditionalGUIProvider {
/**
* Overridable entry point for subclasses that wish to put something to the right of the "Command:" label
* @return true if something entered to take up the available columns, false otherwise (will be padded)
*/
public boolean createCommandLabelLineControls(Composite parent, int availableColumns);
/**
* Create additional buttons, to go under command prompt.
* Overridable.
* @return true if something entered to take up the available columns, false otherwise (will be padded)
*/
public boolean createExtraButtons(Composite parent, int availableColumns);
}

View file

@ -0,0 +1,32 @@
package org.eclipse.rse.useractions.ui;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/**
* Objects implementing this interface are passed to
* {@link SystemCmdSubstVarList} parse a given command
* string for variables defined in the substitution list.
* For each match, this object is called back to retrieve
* the substition value, given the variable name (including
* its prefix). It will also pass back the context object
* given to it. Presumably this is a currently selected object.
*/
public interface ISystemSubstitutor {
/**
* Return the string to substitute for the given substitution
* variable, given the current context object. This object will
* be passed whatever was passed into the doSubstitution method.
* <p>It is VERY IMPORTANT to return null if you can't do the
* substitution for some reason! This is a clue to the algorithm
* that no change was made and increases performance.
*/
public String getSubstitutionValue(String substitutionVariable, Object context);
}

View file

@ -0,0 +1,77 @@
package org.eclipse.rse.useractions.ui;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/**
* @author coulthar
*
* This class encapsulates a single substitution variable.
* Such a variable has the following information:
* <ol>
* <li>The actual variable, as in "&L"
* <li>A translated description of the variable, as in "Library name"
* <li>A display string, which is typically a concatenation of the above two attributes
* </ol>
* Currently this class is not used at runtime to do the actual substitution,
* although that would be a natural next step.
*/
public class SystemCmdSubstVar implements Comparable {
private String var, desc;
// public constants
/**
* Constructor
*/
public SystemCmdSubstVar(String variable, String description) {
super();
this.var = variable;
this.desc = description;
}
/**
* Return the substitution variable. Eg "&x" or "${xxxx}"
*/
public String getVariable() {
return var;
}
/**
* Return the description. Eg "File name"
*/
public String getDescription() {
return desc;
}
/**
* Return the display string. Eg var " - " description
*/
public String getDisplayString() {
return var + " - " + desc; //$NON-NLS-1$
}
// comparable interface method, to enable sorting
/**
* Compare ourself to another instance of this class
* @return -1 we are less than given object, 0 we are equal, 1 we are greater than
*/
public int compareTo(Object o) {
/* only re-use this when we want to bubble longer names to top...
SystemUDASubstVar other = (SystemUDASubstVar)o;
if (var.equals(other.getVariable()))
return 0;
else if (var.length() > other.getVariable().length())
return -1; // we want longer names at the beginning of an ascending list!
else
return 1;
*/
return var.compareTo(((SystemCmdSubstVar) o).getVariable());
}
}

View file

@ -0,0 +1,292 @@
package org.eclipse.rse.useractions.ui;
/*******************************************************************************
* Copyright (c) 2002, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.io.PrintWriter;
import java.util.Arrays;
/**
* @author coulthar
*
* This encapsulates a list of substitution variables.
* The input for the list is the variable prefix (eg "&"), an
* array of variable names (eg "A", "B", etc), plus the
* resource bundle and key-root for getting the variable
* descriptions (will append variable names to the key-root
* to get the resource bundle key).
* <p>
* This class is also used to help with the actual substitutions
* at runtime. The method doSubstitutions will walk the given
* string looking for matches on any of the variables in this
* list, taking care to look for the longer-named variables first,
* and when a match is found, will call back to the given
* implementor of ISystemSubstitutor, to get the substitution
* value. The substitutor will be given the variable name (eg, "N",
* not "&N") and whatever context object was passed into
* doSubstitutions, presumably one of the currently selected
* objects.
*/
public class SystemCmdSubstVarList {
private SystemCmdSubstVar[] list, sortedList;
private char prefix = ' ';
private boolean usingDelimiters = false;
// constants
/**
* Typical substitution variable prefix when using single prefix char: '&'
*/
public static final char SUBST_PREFIX_AMP = '&';
/**
* Typical substitution variable char prefix when using delimiters: "$"
*/
public static final char SUBST_PREFIX_DOLLAR = '$';
/**
* Typical substitution variable char prefix when using delimiters: "{"
*/
public static final char SUBST_PREFIX_BRACE = '}';
/**
* Typical substitution variable string prefix when using delimiters: "{"
*/
public static final String SUBST_PREFIX = "${"; //$NON-NLS-1$
/**
* Typical substitution variable char suffix when using delimiters: "}"
*/
public static final char SUBST_SUFFIX_BRACE = '}';
/**
* Constructor when using single prefix like '&'
*/
public SystemCmdSubstVarList(char prefix, String[] names, String[] descriptions) {
this(null, prefix, names, descriptions);
}
/**
* Constructor when using single prefix like '&', and based on another list
* Sometimes a substitution variable list contains common variables, plus some unique variables.
* In this case, use this construction, and pass in the list object for the common variables.
*/
public SystemCmdSubstVarList(SystemCmdSubstVarList commonList, char prefix, String[] names, String[] descriptions) {
super();
this.prefix = prefix;
init(commonList, names, descriptions);
}
/**
* Constructor when using ${xxx} delimiting, and not based on another list
*/
public SystemCmdSubstVarList(String[] names, String[] descriptions) {
this(null, names, descriptions);
}
/**
* Constructor when using ${xxx} delimiting, and we are based on another list
*/
public SystemCmdSubstVarList(SystemCmdSubstVarList commonList, String[] names, String[] descriptions) {
super();
usingDelimiters = true;
prefix = SUBST_PREFIX_DOLLAR;
init(commonList, names, descriptions);
}
/**
* Abstraction of common stuff done by all constructors.
*/
public void init(SystemCmdSubstVarList commonList, String[] names, String[] descriptions) {
SystemCmdSubstVar[] commonArray = null;
int idx = 0;
if (commonList == null)
list = new SystemCmdSubstVar[names.length];
else {
commonArray = commonList.getListAsArray();
list = new SystemCmdSubstVar[commonArray.length + names.length];
for (; idx < commonArray.length; idx++)
list[idx] = commonArray[idx];
}
String varName = null;
String description = null;
for (int jdx = 0; jdx < names.length; idx++, jdx++) {
if (!usingDelimiters) {
varName = prefix + names[jdx];
} else {
varName = SUBST_PREFIX + names[jdx] + SUBST_SUFFIX_BRACE;
}
description = descriptions[jdx];
list[idx] = new SystemCmdSubstVar(varName, description);
}
// sort list alphabetically...
Arrays.sort(list);
// for testing...
/*
System.out.println("Sorted list: ");
for (int jdx=0; jdx<list.length; jdx++)
System.out.println("..."+list[jdx].getVariable());
System.out.println();
*/
}
/**
* Return the list of variables as an array of SystemCmdSubstVar objects
*/
public SystemCmdSubstVar[] getListAsArray() {
return list;
}
/**
* Return the list as an array of display strings of the form xx - some text
*/
public String[] getDisplayStrings() {
String[] strings = new String[list.length];
for (int idx = 0; idx < strings.length; idx++)
strings[idx] = list[idx].getDisplayString();
return strings;
}
/**
* For debugging purposes, writes the list of variables to standard out
*/
public void printDisplayStrings() {
System.out.println("Substitution Variables for " + getClass().getName()); //$NON-NLS-1$
String[] strings = getDisplayStrings();
for (int idx = 0; idx < strings.length; idx++)
System.out.println(strings[idx]);
System.out.println();
}
/**
* For whatever purpose, writes the list of variables to given stream
*/
public void printDisplayStrings(PrintWriter stream) {
stream.println("Substitution Variables for " + getClass().getName()); //$NON-NLS-1$
String[] strings = getDisplayStrings();
for (int idx = 0; idx < strings.length; idx++)
stream.println(strings[idx]);
stream.println();
}
/**
* Given a command string potentially containing substitution variables,
* and a context object that represents something currently selected (say),
* this will scan the command string for matches on any of the substitution
* variables defined in this list. For each match it calls the given
* implementor of {@link ISystemSubstitutor} to retrieve the value to
* replace the substitution variable with. The substitutor is also given
* the context object passed in here.
* <p>
* Currently this assume all variables use the prefix given in the constructor,
* as it optimizes performance.
* Another flavour would be needed if arbitrary prefixes were to supported!
* <p>
* Further, this also currently assumes a doubled up prefix is used for escaping,
* meaning the first prefix is to be removed, the next is to be left unsubstituted.
*
* @param commandString - the command from the user action, that contains vars to be substituted
* @param context - a selected object
* @param substitutor - an object that knows how to do substitutions. A callback.
*/
public String doSubstitutions(String commandString, Object context, ISystemSubstitutor substitutor) {
//System.out.println("Command before substitution: " + commandString);
// walk the command string, looking for variables...
String part1, part2;
int index = 0;
int lastindex = 0;
//int cmdLength = commandString.length();
while ((index = commandString.indexOf(prefix, lastindex)) >= 0) {
lastindex = index + 1; // start next search at char after this '&'
// ampersand followed by at least one letter?
if (commandString.length() >= (index + 1)) {
char sc = commandString.charAt(index + 1); // char after this '&'
if (sc == prefix) // next char is also an '&'?
{
++lastindex; // skip it. Note its ok to bump it past length of string
} else {
String var = findMatchingVar(commandString, index);
if (var != null) {
String replacement = substitutor.getSubstitutionValue(var, context);
if (replacement != null) {
if (index == 0) // substitution variable at front of command?
commandString = commandString.substring(index + var.length());
else {
part1 = commandString.substring(0, index);
part2 = commandString.substring(index + var.length());
commandString = part1 + replacement + part2;
}
lastindex = index + replacement.length(); // assume replacement has no '&' chars in it!
}
}
}
}
} // end while
//System.out.println("Command after substitution : " + commandString);
//System.out.println();
return commandString;
}
/**
* For testing purposes.
* Given the selected object, this returns an array of strings, one for each substitution
* variable, of the form "varname = substituted-value".
* @param context - a selected object
* @param substitutor - an object that knows how to do substitutions. A callback
*/
public String[] doAllSubstitutions(Object context, ISystemSubstitutor substitutor) {
String[] substitutedVariables = new String[list.length];
String currVar = null;
for (int idx = 0; idx < list.length; idx++) {
currVar = list[idx].getVariable();
substitutedVariables[idx] = currVar + " = " + //$NON-NLS-1$
doSubstitutions("\"" + currVar + "\"", context, substitutor); //$NON-NLS-1$ //$NON-NLS-2$
}
return substitutedVariables;
}
/**
* Check our list of sub vars for a match on given string at given index
*/
private String findMatchingVar(String cmd, int indexOfPrefix) {
if (sortedList == null) {
sortedList = list;
/*
* At this point we don't need to sort names as we are careful not
* to define variables that are ambiguous. Eg, &A and &AB.
*
sortedList = new SystemUDASubstVar[list.length];
for (int i = 0; i < sortedList.length; i++)
sortedList[i] = list[i];
Arrays.sort(sortedList);
*/
}
int cmdlen = cmd.length();
for (int idx = 0; idx < sortedList.length; idx++) {
String var = sortedList[idx].getVariable();
int varlen = var.length();
if (((indexOfPrefix + varlen) <= cmdlen) && var.equals(cmd.substring(indexOfPrefix, indexOfPrefix + varlen))) return var;
}
return null;
}
/**
* Helper method to test for duplicate variables
*/
public void testForDuplicates() {
String currname = null;
for (int idx = 0; idx < list.length; idx++) {
currname = list[idx].getVariable();
for (int i = 0; i < list.length; i++)
if (i != idx) if (list[i].equals(currname)) System.out.println("duplicate subs var " + currname + " in list " + this.getClass().getName()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* This writes out the class name.
*/
public String toString() {
return getClass().getName();
}
}

Some files were not shown because too many files have changed in this diff Show more