Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 245565 | Differences between
and this patch

Collapse All | Expand All

(-)src/org/eclipse/pde/internal/ui/wizards/imports/PluginImportWizard.java (-17 / +5 lines)
Lines 11-18 Link Here
11
package org.eclipse.pde.internal.ui.wizards.imports;
11
package org.eclipse.pde.internal.ui.wizards.imports;
12
12
13
import java.util.*;
13
import java.util.*;
14
import org.eclipse.core.runtime.*;
14
import org.eclipse.core.resources.ResourcesPlugin;
15
import org.eclipse.core.runtime.jobs.Job;
15
import org.eclipse.core.runtime.CoreException;
16
import org.eclipse.debug.core.*;
16
import org.eclipse.debug.core.*;
17
import org.eclipse.jface.dialogs.*;
17
import org.eclipse.jface.dialogs.*;
18
import org.eclipse.jface.viewers.IStructuredSelection;
18
import org.eclipse.jface.viewers.IStructuredSelection;
Lines 133-153 Link Here
133
	}
133
	}
134
134
135
	private static void doImportOperation(final Shell shell, final int importType, final IPluginModelBase[] models, final boolean forceAutobuild, final boolean launchedConfiguration) {
135
	private static void doImportOperation(final Shell shell, final int importType, final IPluginModelBase[] models, final boolean forceAutobuild, final boolean launchedConfiguration) {
136
		PluginImportOperation.IImportQuery query = new ImportQuery(shell);
136
		PluginImportOperation job = new PluginImportOperation(models, importType, new ImportQuery(shell), new ImportQuery(shell), forceAutobuild);
137
		PluginImportOperation.IImportQuery executionQuery = new ImportQuery(shell);
137
		job.setPluginsInUse(launchedConfiguration);
138
		final PluginImportOperation op = new PluginImportOperation(models, importType, query, executionQuery, forceAutobuild);
138
		job.setRule(ResourcesPlugin.getWorkspace().getRoot());
139
		op.setLaunchedConfiguration(launchedConfiguration);
140
		Job job = new Job(PDEUIMessages.ImportWizard_title) {
141
			protected IStatus run(IProgressMonitor monitor) {
142
				try {
143
					PDEPlugin.getWorkspace().run(op, monitor);
144
				} catch (CoreException e) {
145
					PDEPlugin.logException(e);
146
					return Status.CANCEL_STATUS;
147
				}
148
				return Status.OK_STATUS;
149
			}
150
		};
151
		job.setUser(true);
139
		job.setUser(true);
152
		job.schedule();
140
		job.schedule();
153
	}
141
	}
(-)src/org/eclipse/pde/internal/ui/wizards/imports/PluginImportOperation.java (-765 / +471 lines)
Lines 14-20 Link Here
14
import java.io.IOException;
14
import java.io.IOException;
15
import java.util.*;
15
import java.util.*;
16
import java.util.jar.JarFile;
16
import java.util.jar.JarFile;
17
import java.util.zip.ZipEntry;
18
import java.util.zip.ZipFile;
17
import java.util.zip.ZipFile;
19
import org.eclipse.core.resources.*;
18
import org.eclipse.core.resources.*;
20
import org.eclipse.core.runtime.*;
19
import org.eclipse.core.runtime.*;
Lines 22-30 Link Here
22
import org.eclipse.jdt.core.*;
21
import org.eclipse.jdt.core.*;
23
import org.eclipse.jdt.launching.JavaRuntime;
22
import org.eclipse.jdt.launching.JavaRuntime;
24
import org.eclipse.jdt.launching.environments.IExecutionEnvironmentsManager;
23
import org.eclipse.jdt.launching.environments.IExecutionEnvironmentsManager;
25
import org.eclipse.osgi.service.environment.Constants;
26
import org.eclipse.osgi.service.resolver.BundleDescription;
24
import org.eclipse.osgi.service.resolver.BundleDescription;
27
import org.eclipse.osgi.service.resolver.HostSpecification;
28
import org.eclipse.osgi.util.ManifestElement;
25
import org.eclipse.osgi.util.ManifestElement;
29
import org.eclipse.osgi.util.NLS;
26
import org.eclipse.osgi.util.NLS;
30
import org.eclipse.pde.core.build.IBuild;
27
import org.eclipse.pde.core.build.IBuild;
Lines 38-44 Link Here
38
import org.eclipse.pde.internal.core.util.CoreUtility;
35
import org.eclipse.pde.internal.core.util.CoreUtility;
39
import org.eclipse.pde.internal.ui.PDEPlugin;
36
import org.eclipse.pde.internal.ui.PDEPlugin;
40
import org.eclipse.pde.internal.ui.PDEUIMessages;
37
import org.eclipse.pde.internal.ui.PDEUIMessages;
41
import org.eclipse.swt.widgets.Display;
42
import org.eclipse.team.core.RepositoryProvider;
38
import org.eclipse.team.core.RepositoryProvider;
43
import org.eclipse.team.core.TeamException;
39
import org.eclipse.team.core.TeamException;
44
import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
40
import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
Lines 46-61 Link Here
46
import org.osgi.framework.BundleException;
42
import org.osgi.framework.BundleException;
47
43
48
/**
44
/**
49
 * Imports one or more plugins into the workspace.  There are three different
45
 * Imports one or more plug-ins into the workspace.  There are three different
50
 * ways to import a plugin: as binary, as binary with linked source,
46
 * ways to import a plugin: as binary, as binary with linked source,
51
 * and as source. 
47
 * and as source. 
52
 */
48
 */
53
public class PluginImportOperation extends JarImportOperation {
49
public class PluginImportOperation extends Job {
54
50
55
	public static final int IMPORT_BINARY = 1;
51
	public static final int IMPORT_BINARY = 1;
56
	public static final int IMPORT_BINARY_WITH_LINKS = 2;
52
	public static final int IMPORT_BINARY_WITH_LINKS = 2;
57
	public static final int IMPORT_WITH_SOURCE = 3;
53
	public static final int IMPORT_WITH_SOURCE = 3;
58
54
55
	private static final String DEFAULT_SOURCE_DIR = "src"; //$NON-NLS-1$
56
	private static final String DEFAULT_LIBRARY_NAME = "."; //$NON-NLS-1$
57
59
	private IPluginModelBase[] fModels;
58
	private IPluginModelBase[] fModels;
60
	private int fImportType;
59
	private int fImportType;
61
	private IImportQuery fReplaceQuery;
60
	private IImportQuery fReplaceQuery;
Lines 63-73 Link Here
63
	private boolean fForceAutobuild;
62
	private boolean fForceAutobuild;
64
	private IImportQuery fExecutionQuery;
63
	private IImportQuery fExecutionQuery;
65
64
66
	private boolean fLaunchedConfigurations = false;
65
	private boolean fPluginsAreInUse = false;
67
	/**
68
	 * A list of plugins that were unable to be deleted
69
	 */
70
	private ArrayList fUnableToDeletePlugins;
71
66
72
	public interface IImportQuery {
67
	public interface IImportQuery {
73
		public static final int CANCEL = 0;
68
		public static final int CANCEL = 0;
Lines 83-189 Link Here
83
	 * @param importType one of three types specified by constants, binary, binary with links, source
78
	 * @param importType one of three types specified by constants, binary, binary with links, source
84
	 * @param replaceQuery defines what to do if the project already exists in the workspace
79
	 * @param replaceQuery defines what to do if the project already exists in the workspace
85
	 * @param executionQuery defines what to do if the project requires an unsupported execution environment
80
	 * @param executionQuery defines what to do if the project requires an unsupported execution environment
81
	 * @param forceAutobuild whether to force a build after the import
86
	 */
82
	 */
87
	public PluginImportOperation(IPluginModelBase[] models, int importType, IImportQuery replaceQuery, IImportQuery executionQuery) {
83
	public PluginImportOperation(IPluginModelBase[] models, int importType, IImportQuery replaceQuery, IImportQuery executionQuery, boolean forceAutobuild) {
84
		super(PDEUIMessages.ImportWizard_title);
88
		fModels = models;
85
		fModels = models;
89
		fImportType = importType;
86
		fImportType = importType;
90
		fReplaceQuery = replaceQuery;
87
		fReplaceQuery = replaceQuery;
91
		fExecutionQuery = executionQuery;
88
		fExecutionQuery = executionQuery;
92
		fUnableToDeletePlugins = new ArrayList();
89
		fForceAutobuild = forceAutobuild;
93
	}
90
	}
94
91
95
	/**
92
	/**
96
	 * Constructor
93
	 * Sets whether some of the plug-ins being imported are currently in use by a launched
97
	 * @param models models of plugins to import
94
	 * Eclipse instance.  Setting this to true will force an additional check before deleting
98
	 * @param importType one of three types specified by constants, binary, binary with links, source
95
	 * a plug-in.
99
	 * @param replaceQuery defines what to do if the project already exists in the workspace
96
	 * @param pluginsInUse
100
	 * @param executionQuery defines what to do if the project requires an unsupported execution environment
101
	 * @param forceAutobuild whether to force a build after the import
102
	 */
97
	 */
103
	public PluginImportOperation(IPluginModelBase[] models, int importType, IImportQuery replaceQuery, IImportQuery executionQuery, boolean forceAutobuild) {
98
	public void setPluginsInUse(boolean pluginsInUse) {
104
		this(models, importType, replaceQuery, executionQuery);
99
		fPluginsAreInUse = pluginsInUse;
105
		fForceAutobuild = forceAutobuild;
106
	}
100
	}
107
101
108
	/* (non-Javadoc)
102
	/* (non-Javadoc)
109
	 * @see org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor)
103
	 * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
110
	 */
104
	 */
111
	public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
105
	protected IStatus run(IProgressMonitor monitor) {
112
		if (monitor == null) {
113
			monitor = new NullProgressMonitor();
114
		}
115
		monitor.beginTask(PDEUIMessages.ImportWizard_operation_creating, fModels.length + 1);
116
		try {
106
		try {
107
			monitor.beginTask(PDEUIMessages.ImportWizard_operation_creating, fModels.length + 1);
117
			MultiStatus multiStatus = new MultiStatus(PDEPlugin.getPluginId(), IStatus.OK, PDEUIMessages.ImportWizard_operation_multiProblem, null);
108
			MultiStatus multiStatus = new MultiStatus(PDEPlugin.getPluginId(), IStatus.OK, PDEUIMessages.ImportWizard_operation_multiProblem, null);
118
109
119
			for (int i = 0; i < fModels.length; i++) {
110
			for (int i = 0; i < fModels.length; i++) {
111
				monitor.setTaskName(NLS.bind(PDEUIMessages.PluginImportOperation_Importing_plugin, fModels[i].getPluginBase().getId()));
120
				try {
112
				try {
121
					importPlugin(fModels[i], new SubProgressMonitor(monitor, 1));
113
					importPlugin(fModels[i], new SubProgressMonitor(monitor, 1));
122
				} catch (CoreException e) {
114
				} catch (CoreException e) {
123
					multiStatus.merge(e.getStatus());
115
					multiStatus.merge(e.getStatus());
124
				}
116
				}
125
				if (monitor.isCanceled()) {
117
				if (monitor.isCanceled()) {
126
					setClasspaths(new SubProgressMonitor(monitor, 1));
118
					try {
127
					throw new OperationCanceledException();
119
						setClasspaths(new SubProgressMonitor(monitor, 1));
120
					} catch (JavaModelException e) {
121
						/* Do nothing as we are already cancelled */
122
					}
123
					return Status.CANCEL_STATUS;
128
				}
124
				}
129
			}
125
			}
130
			setClasspaths(new SubProgressMonitor(monitor, 1));
126
			try {
127
				setClasspaths(new SubProgressMonitor(monitor, 1));
128
			} catch (JavaModelException e) {
129
				multiStatus.merge(e.getStatus());
130
			}
131
			if (!ResourcesPlugin.getWorkspace().isAutoBuilding() && fForceAutobuild)
131
			if (!ResourcesPlugin.getWorkspace().isAutoBuilding() && fForceAutobuild)
132
				runBuildJob();
132
				runBuildJob();
133
			if (!multiStatus.isOK())
133
			return multiStatus;
134
				throw new CoreException(multiStatus);
135
		} finally {
134
		} finally {
136
			monitor.done();
135
			monitor.done();
137
			if (!fUnableToDeletePlugins.isEmpty()) {
138
				final Display display = Display.getDefault();
139
				display.syncExec(new Runnable() {
140
					public void run() {
141
						PluginImportFinishDialog dialog = new PluginImportFinishDialog(display.getActiveShell());
142
						dialog.setTitle(PDEUIMessages.PluginImportInfoDialog_title);
143
						dialog.setMessage(PDEUIMessages.PluginImportInfoDialog_message);
144
						dialog.setInput(fUnableToDeletePlugins);
145
						dialog.open();
146
					}
147
148
				});
149
			}
150
		}
136
		}
151
	}
137
	}
152
138
153
	/**
139
	/**
154
	 * Starts a job that will build the workspace
155
	 */
156
	private void runBuildJob() {
157
		Job buildJob = new Job(PDEUIMessages.CompilersConfigurationBlock_building) {
158
			public boolean belongsTo(Object family) {
159
				return ResourcesPlugin.FAMILY_AUTO_BUILD == family;
160
			}
161
162
			protected IStatus run(IProgressMonitor monitor) {
163
				try {
164
					PDEPlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
165
				} catch (CoreException e) {
166
				}
167
				return Status.OK_STATUS;
168
			}
169
		};
170
		buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule());
171
		buildJob.schedule();
172
	}
173
174
	/**
175
	 * Sets the raw classpath of projects that need to be updated
140
	 * Sets the raw classpath of projects that need to be updated
176
	 * @param monitor
141
	 * @param monitor
177
	 * @throws JavaModelException if a classpath could not be set
142
	 * @throws JavaModelException if a classpath could not be set
178
	 */
143
	 */
179
	private void setClasspaths(IProgressMonitor monitor) throws JavaModelException {
144
	private void setClasspaths(IProgressMonitor monitor) throws JavaModelException {
180
		monitor.beginTask("", fProjectClasspaths.size()); //$NON-NLS-1$
145
		try {
181
		Enumeration keys = fProjectClasspaths.keys();
146
			monitor.beginTask("", fProjectClasspaths.size()); //$NON-NLS-1$
182
		while (keys.hasMoreElements()) {
147
			Enumeration keys = fProjectClasspaths.keys();
183
			IProject project = (IProject) keys.nextElement();
148
			while (keys.hasMoreElements()) {
184
			IClasspathEntry[] classpath = (IClasspathEntry[]) fProjectClasspaths.get(project);
149
				IProject project = (IProject) keys.nextElement();
185
			monitor.subTask(project.getName());
150
				IClasspathEntry[] classpath = (IClasspathEntry[]) fProjectClasspaths.get(project);
186
			JavaCore.create(project).setRawClasspath(classpath, new SubProgressMonitor(monitor, 1));
151
				monitor.subTask(project.getName());
152
				JavaCore.create(project).setRawClasspath(classpath, new SubProgressMonitor(monitor, 1));
153
			}
154
		} finally {
155
			monitor.done();
187
		}
156
		}
188
	}
157
	}
189
158
Lines 196-314 Link Here
196
	 * @throws CoreException if a problem occurs while importing a plugin
165
	 * @throws CoreException if a problem occurs while importing a plugin
197
	 */
166
	 */
198
	private void importPlugin(IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
167
	private void importPlugin(IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
199
		String id = model.getPluginBase().getId();
200
		monitor.beginTask(NLS.bind(PDEUIMessages.ImportWizard_operation_creating2, id), 6);
201
		try {
168
		try {
202
			BundleDescription desc = model.getBundleDescription();
169
			monitor.beginTask("", 5); //$NON-NLS-1$
203
			if (desc != null) {
204
				IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
205
				String[] envs = desc.getExecutionEnvironments();
206
				boolean found = false;
207
				for (int i = 0; i < envs.length; i++) {
208
					if (manager.getEnvironment(envs[i]) != null) {
209
						found = true;
210
						break;
211
					}
212
				}
213
				if (envs.length > 0 && !found) {
214
					String message = NLS.bind(PDEUIMessages.PluginImportOperation_executionEnvironment, id, envs[0]);
215
					if (!queryExecutionEnvironment(message))
216
						return;
217
				}
218
			}
219
170
220
			IProject project = findProject(id);
171
			// Test is the required execution environment is supported
221
172
			if (!testExecutionEnvironment(model)) {
222
			if (project.exists() || new File(project.getParent().getLocation().toFile(), project.getName()).exists()) {
173
				return;
223
				if (!queryReplace(project))
224
					return;
225
				if (RepositoryProvider.isShared(project))
226
					RepositoryProvider.unmap(project);
227
				if (!project.exists())
228
					project.create(new SubProgressMonitor(monitor, 1));
229
				if (!safeDeleteCheck(project, monitor)) {
230
					fUnableToDeletePlugins.add(model);
231
					return;
232
				}
233
				try {
234
					project.delete(true, true, monitor);
235
				} catch (CoreException e) {
236
					fUnableToDeletePlugins.add(model);
237
					return;
238
				}
239
			}
174
			}
175
			// Create the project or ask to overwrite if project exists
176
			IProject project = createProject(model, new SubProgressMonitor(monitor, 1));
240
177
241
			project.create(monitor);
178
			// Target Weaving: if we are importing plug-ins in the runtime workbench from the host workbench, import everything as-is and return
242
			if (!project.isOpen())
243
				project.open(monitor);
244
			monitor.worked(1);
245
246
			if (Platform.inDevelopmentMode()) {
179
			if (Platform.inDevelopmentMode()) {
247
				// if we are importing plug-ins in the runtime workbench from the host workbench, import everything as-is and return
248
				File location = new File(model.getInstallLocation());
180
				File location = new File(model.getInstallLocation());
249
				if (location.isDirectory()) {
181
				if (location.isDirectory()) {
250
					File classpathFile = new File(location, ".classpath"); //$NON-NLS-1$
182
					File classpathFile = new File(location, ".classpath"); //$NON-NLS-1$
251
					File projectFile = new File(location, ".project"); //$NON-NLS-1$
183
					File projectFile = new File(location, ".project"); //$NON-NLS-1$
252
					if (classpathFile.exists() && classpathFile.isFile() && projectFile.exists() && projectFile.isFile()) {
184
					if (classpathFile.exists() && classpathFile.isFile() && projectFile.exists() && projectFile.isFile()) {
253
						importContent(location, project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, new SubProgressMonitor(monitor, 1));
185
						PluginImportHelper.importContent(location, project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, new SubProgressMonitor(monitor, 4));
254
						return;
186
						return;
255
					}
187
					}
256
				}
188
				}
257
			}
189
			}
258
190
259
			switch (fImportType) {
191
			// Perform the import
260
				case IMPORT_BINARY :
192
			Map sourceMap = null;
261
					importAsBinary(project, model, true, new SubProgressMonitor(monitor, 4));
193
			if (fImportType == IMPORT_BINARY || isExempt(model)) {
262
					break;
194
				sourceMap = importAsBinary(project, model, new SubProgressMonitor(monitor, 4));
263
				case IMPORT_BINARY_WITH_LINKS :
195
			} else if (fImportType == IMPORT_BINARY_WITH_LINKS) {
264
					if (id.startsWith("org.eclipse.swt") && !isJARd(model)) { //$NON-NLS-1$
196
				sourceMap = importAsBinaryWithLinks(project, model, new SubProgressMonitor(monitor, 4));
265
						importAsBinary(project, model, true, monitor);
197
			} else if (fImportType == IMPORT_WITH_SOURCE) {
266
					} else {
198
				importAsSource(project, model, new SubProgressMonitor(monitor, 4));
267
						importAsBinaryWithLinks(project, model, new SubProgressMonitor(monitor, 4));
268
					}
269
					break;
270
				case IMPORT_WITH_SOURCE :
271
					if (isExempt(model)) {
272
						importAsBinary(project, model, true, new SubProgressMonitor(monitor, 4));
273
					} else {
274
						importAsSource(project, model, new SubProgressMonitor(monitor, 4));
275
					}
276
			}
199
			}
277
200
278
			setProjectDescription(project, model);
201
			setProjectNatures(project, model);
279
202
203
			// Set the classpath
280
			if (project.hasNature(JavaCore.NATURE_ID) && project.findMember(".classpath") == null) //$NON-NLS-1$
204
			if (project.hasNature(JavaCore.NATURE_ID) && project.findMember(".classpath") == null) //$NON-NLS-1$
281
				fProjectClasspaths.put(project, ClasspathComputer.getClasspath(project, model, true, false));
205
				fProjectClasspaths.put(project, ClasspathComputer.getClasspath(project, model, sourceMap, true, false));
282
		} catch (CoreException e) {
283
			PDEPlugin.logException(e);
284
		} finally {
206
		} finally {
285
			monitor.done();
207
			monitor.done();
286
		}
208
		}
287
	}
209
	}
288
210
289
	// Returns the name of any projects the currently exist with same id and version.  Otherwise it returns a default naming convention
211
	/**
290
	protected String getProjectName(IPluginModelBase model) {
212
	 * Imports the contents of the plugin and imports source files as binary files that will not be compiled.
291
		String id = model.getPluginBase().getId();
213
	 * @param project destination project of the import
292
		String version = model.getPluginBase().getVersion();
214
	 * @param model model representing the plugin to import
293
		ModelEntry entry = PluginRegistry.findEntry(id);
215
	 * @param monitor progress monitor
294
		if (entry != null) {
216
	 * @return a mapping of libraries to source locations to use in the classpath
295
			IPluginModelBase[] existingModels = entry.getWorkspaceModels();
217
	 * @throws CoreException if there is a problem completing the import
296
			for (int i = 0; i < existingModels.length; i++) {
218
	 */
297
				String existingVersion = existingModels[i].getPluginBase().getVersion();
219
	private Map importAsBinary(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
298
				if (version.equals(existingVersion)) {
220
		try {
299
					IResource res = existingModels[i].getUnderlyingResource();
221
			monitor.beginTask("", 3); //$NON-NLS-1$
300
					if (res != null)
222
301
						return res.getProject().getName();
223
			// Import the plug-in content
224
			File srcFile = new File(model.getInstallLocation());
225
			if (isJARd(model)) {
226
				PluginImportHelper.copyArchive(srcFile, project.getFile(srcFile.getName()), new SubProgressMonitor(monitor, 1));
227
			} else {
228
				PluginImportHelper.importContent(new File(model.getInstallLocation()), project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, new SubProgressMonitor(monitor, 1));
229
			}
230
231
			// Import source from known source locations
232
			Map sourceMap = importSourceArchives(project, model, IMPORT_BINARY, new SubProgressMonitor(monitor, 1));
233
234
			// Extract the required bundle files and modify the imported manifest to have the correct classpath
235
			importRequiredPluginFiles(project, model, new SubProgressMonitor(monitor, 1));
236
			modifyBundleClasspathHeader(project, model);
237
238
			// Mark the project as binary
239
			project.setPersistentProperty(PDECore.EXTERNAL_PROJECT_PROPERTY, PDECore.BINARY_PROJECT_VALUE);
240
			RepositoryProvider.map(project, PDECore.BINARY_REPOSITORY_PROVIDER);
241
242
			return sourceMap;
243
244
		} finally {
245
			monitor.done();
246
		}
247
	}
248
249
	/**
250
	 * Creates links to remote plugin and source locations and sets up the project
251
	 * @param project destination project of the import
252
	 * @param model model representing the plugin to import
253
	 * @param monitor progress monitor
254
	 * @return mapping of library name to path to source library (relative to project)
255
	 * @throws CoreException if there is a problem completing the import
256
	 */
257
	private Map importAsBinaryWithLinks(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
258
		try {
259
			monitor.beginTask("", 3); //$NON-NLS-1$
260
261
			// Link the plug-in content
262
			File srcFile = new File(model.getInstallLocation());
263
			IFile dstFile = project.getFile(new Path(srcFile.getName()));
264
			dstFile.createLink(srcFile.toURI(), IResource.NONE, new SubProgressMonitor(monitor, 1));
265
266
			// Link source from known source locations
267
			Map sourceMap = importSourceArchives(project, model, IMPORT_BINARY_WITH_LINKS, new SubProgressMonitor(monitor, 1));
268
269
			// Extract the required bundle files and modify the imported manifest to have the correct classpath
270
			importRequiredPluginFiles(project, model, new SubProgressMonitor(monitor, 1));
271
			modifyBundleClasspathHeader(project, model);
272
273
			// Mark the project as binary
274
			project.setPersistentProperty(PDECore.EXTERNAL_PROJECT_PROPERTY, PDECore.BINARY_PROJECT_VALUE);
275
			RepositoryProvider.map(project, PDECore.BINARY_REPOSITORY_PROVIDER);
276
277
			return sourceMap;
278
279
		} finally {
280
			monitor.done();
281
		}
282
	}
283
284
	/**
285
	 * Imports the contents of the plugin and imports source files to source folders that will be compiled.
286
	 * @param project destination project of the import
287
	 * @param model model representing the plugin to import
288
	 * @param monitor progress monitor
289
	 * @throws CoreException if there is a problem completing the import
290
	 */
291
	private void importAsSource(IProject project, IPluginModelBase model, SubProgressMonitor monitor) throws CoreException {
292
		try {
293
			monitor.beginTask("", 4); //$NON-NLS-1$
294
295
			// Extract the source
296
			WorkspaceBuildModel buildModel = extractSourceFolders(project, model, new SubProgressMonitor(monitor, 1));
297
298
			// Extract additional non-java files from the source bundles
299
			importAdditionalSourceFiles(project, model, new SubProgressMonitor(monitor, 1));
300
301
			// Extract the binary plug-in (for non-class files)
302
			File srcFile = new File(model.getInstallLocation());
303
			if (isJARd(model)) {
304
				PluginImportHelper.extractArchive(srcFile, project.getFullPath(), new SubProgressMonitor(monitor, 1));
305
			} else {
306
				// TODO This might put everything into a folder, which is bad
307
				PluginImportHelper.importContent(new File(model.getInstallLocation()), project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, new SubProgressMonitor(monitor, 1));
308
			}
309
310
			// Create the build.properties file
311
			configureBinIncludes(buildModel, model, project);
312
			buildModel.save();
313
			monitor.worked(1);
314
315
		} finally {
316
			monitor.done();
317
		}
318
319
	}
320
321
	/**
322
	 * Creates the project to add to the workspace.  If the project already exists in 
323
	 * the workspace ask the user if it is ok to overwrite.  Will return <code>null</code>
324
	 * if no project could be created for the import (i.e. the user chooses to not overwrite).
325
	 * 
326
	 * @param model plug-in being imported
327
	 * @param monitor progress monitor
328
	 * @return the project to use or <code>null</code> if no project could be created/overwritten
329
	 * @throws TeamException if an existing project is shared and an error occurs disconnecting it
330
	 * @throws CoreException if an error occurs when working with the project
331
	 */
332
	private IProject createProject(IPluginModelBase model, IProgressMonitor monitor) throws TeamException, CoreException {
333
		try {
334
			monitor.beginTask("", 2); //$NON-NLS-1$
335
			IProject project = findProject(model.getPluginBase().getId());
336
			if (project.exists() || new File(project.getParent().getLocation().toFile(), project.getName()).exists()) {
337
				// Query the user to see if we should overwrite
338
				switch (fReplaceQuery.doQuery(NLS.bind(PDEUIMessages.ImportWizard_messages_exists, project.getName()))) {
339
					case IImportQuery.CANCEL :
340
						throw new OperationCanceledException();
341
					case IImportQuery.NO :
342
						return null;
302
				}
343
				}
344
				if (RepositoryProvider.isShared(project))
345
					RepositoryProvider.unmap(project);
346
				if (!project.exists())
347
					project.create(new SubProgressMonitor(monitor, 1));
348
				if (!safeDeleteCheck(project, monitor)) {
349
					throw new CoreException(new Status(IStatus.ERROR, PDEPlugin.getPluginId(), NLS.bind(PDEUIMessages.PluginImportOperation_could_not_delete_project, project.getName())));
350
				}
351
				project.delete(true, true, monitor);
303
			}
352
			}
353
354
			project.create(monitor);
355
			if (!project.isOpen())
356
				project.open(monitor);
357
			monitor.worked(1);
358
359
			return project;
360
361
		} finally {
362
			monitor.done();
304
		}
363
		}
305
		return id + "_" + version; //$NON-NLS-1$
306
	}
364
	}
307
365
308
	// returns true if it is safe to delete the project.  It is not safe to delete if
366
	private IProject findProject(String id) {
309
	// one of its libraries is locked by a running launch configuration.
367
		IPluginModelBase model = PluginRegistry.findModel(id);
368
		if (model != null) {
369
			IResource resource = model.getUnderlyingResource();
370
			if (resource != null)
371
				return resource.getProject();
372
		}
373
		return PDEPlugin.getWorkspace().getRoot().getProject(id);
374
	}
375
376
	/**
377
	 * Returns true if it is safe to delete the project.  It is not safe to delete if
378
	 * one of its libraries is locked by a running launch configuration.
379
	 * 
380
	 * @param project project to test
381
	 * @param monitor progress monitor
382
	 * @return true is it is safe to delete the project, false otherwise
383
	 */
310
	private boolean safeDeleteCheck(IProject project, IProgressMonitor monitor) {
384
	private boolean safeDeleteCheck(IProject project, IProgressMonitor monitor) {
311
		if (!fLaunchedConfigurations)
385
		if (!fPluginsAreInUse)
312
			return true;
386
			return true;
313
		IPluginModelBase base = PluginRegistry.findModel(project);
387
		IPluginModelBase base = PluginRegistry.findModel(project);
314
		if (base != null) {
388
		if (base != null) {
Lines 328-622 Link Here
328
	}
402
	}
329
403
330
	/**
404
	/**
331
	 * Imports the contents of the plugin and adds links to the source location(s).
405
	 * Tests whether the required execution environment of the given plugin is supported by
332
	 * @param project destination project of the import
406
	 * the current known JREs.  If not, ask the user whether to continue.
333
	 * @param model model representing the plugin to import
407
	 * @param model the plug-in model to test
334
	 * @param monitor progress monitor
408
	 * @return true is the import should continue, false if the plug-in should be skipped
335
	 * @throws CoreException if there is a problem completing the import
409
	 * @throws OperationCanceledException if the user chooses to cancel the operation
336
	 */
410
	 */
337
	private void importAsBinaryWithLinks(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
411
	private boolean testExecutionEnvironment(IPluginModelBase model) throws OperationCanceledException {
338
		if (isJARd(model)) {
412
		BundleDescription desc = model.getBundleDescription();
339
			extractJARdPlugin(project, model, monitor);
413
		if (desc != null) {
340
		} else {
414
			IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
341
			File installLocation = new File(model.getInstallLocation());
415
			String[] envs = desc.getExecutionEnvironments();
342
			File[] items = installLocation.listFiles();
416
			boolean found = false;
343
			if (items != null) {
417
			for (int i = 0; i < envs.length; i++) {
344
				monitor.beginTask(PDEUIMessages.PluginImportOperation_linking, items.length + 1);
418
				if (manager.getEnvironment(envs[i]) != null) {
345
				for (int i = 0; i < items.length; i++) {
419
					found = true;
346
					File sourceFile = items[i];
420
					break;
347
					String name = sourceFile.getName();
421
				}
348
					if (sourceFile.isDirectory()) {
422
			}
349
						project.getFolder(name).createLink(new Path(sourceFile.getPath()), IResource.NONE, new SubProgressMonitor(monitor, 1));
423
			if (envs.length > 0 && !found) {
350
					} else {
424
				switch (fExecutionQuery.doQuery(NLS.bind(PDEUIMessages.PluginImportOperation_executionEnvironment, model.getPluginBase().getId(), envs[0]))) {
351
						if (!name.equals(".project")) { //$NON-NLS-1$ 
425
					case IImportQuery.CANCEL :
352
							project.getFile(name).createLink(new Path(sourceFile.getPath()), IResource.NONE, new SubProgressMonitor(monitor, 1));
426
						throw new OperationCanceledException();
353
						} else {
427
					case IImportQuery.NO :
354
							// if the binary project with links has a .project file, copy it instead of linking (allows us to edit it)
428
						return false;
355
							ArrayList filesToImport = new ArrayList(1);
356
							filesToImport.add(sourceFile);
357
							importContent(installLocation, project.getFullPath(), FileSystemStructureProvider.INSTANCE, filesToImport, new SubProgressMonitor(monitor, 1));
358
						}
359
					}
360
				}
429
				}
361
			}
430
			}
362
			linkSourceArchives(project, model, new SubProgressMonitor(monitor, 1));
363
		}
364
		try {
365
			RepositoryProvider.map(project, PDECore.BINARY_REPOSITORY_PROVIDER);
366
		} catch (TeamException e) {
367
			PDECore.logException(e);
368
		}
431
		}
432
		return true;
369
	}
433
	}
370
434
371
	/**
435
	/**
372
	 * Imports the contents of the plugin and imports source files as binary files that will not be compiled.
436
	 * Returns true if the given plugin must be imported as
373
	 * @param project destination project of the import
437
	 * binary instead of the setting defined by fImportType
374
	 * @param model model representing the plugin to import
438
	 * @param model
375
	 * @param markAsBinary whether to mark the project as a binary project
439
	 * @return true is the plugin must be imported as binary, false otherwise
376
	 * @param monitor progress monitor
377
	 * @throws CoreException if there is a problem completing the import
378
	 */
440
	 */
379
	private void importAsBinary(IProject project, IPluginModelBase model, boolean markAsBinary, IProgressMonitor monitor) throws CoreException {
441
	private boolean isExempt(IPluginModelBase model) {
380
		monitor.beginTask("", 4); //$NON-NLS-1$
442
		String id = model.getPluginBase().getId();
381
		if (isJARd(model)) {
443
		if (fImportType == IMPORT_WITH_SOURCE) {
382
			extractJARdPlugin(project, model, new SubProgressMonitor(monitor, 3));
444
			if ("org.apache.ant".equals(id) //$NON-NLS-1$
383
		} else {
445
					|| "org.eclipse.osgi.util".equals(id) //$NON-NLS-1$
384
			importContent(new File(model.getInstallLocation()), project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, new SubProgressMonitor(monitor, 1));
446
					|| "org.eclipse.osgi.services".equals(id) //$NON-NLS-1$
385
			importSourceArchives(project, model, new SubProgressMonitor(monitor, 1));
447
					|| "org.eclipse.core.runtime.compatibility.registry".equals(id)) { //$NON-NLS-1$
448
				return true;
449
			}
450
		}
451
452
		if ("org.eclipse.swt".equals(id) && !isJARd(model)) //$NON-NLS-1$
453
			return true;
454
		return false;
455
	}
386
456
387
			// make sure all libraries have been imported
457
	/**
388
			// if any are missing, check in fragments		
458
	 * Starts a job that will build the workspace
389
			IFragment[] fragments = getFragmentsFor(model);
459
	 */
390
			IPluginLibrary[] libraries = model.getPluginBase().getLibraries();
460
	private void runBuildJob() {
461
		Job buildJob = new Job(PDEUIMessages.CompilersConfigurationBlock_building) {
462
			public boolean belongsTo(Object family) {
463
				return ResourcesPlugin.FAMILY_AUTO_BUILD == family;
464
			}
391
465
392
			IProgressMonitor fragmentMonitor = new SubProgressMonitor(monitor, 1);
466
			protected IStatus run(IProgressMonitor monitor) {
393
			fragmentMonitor.beginTask("", libraries.length); //$NON-NLS-1$
467
				try {
394
			for (int i = 0; i < libraries.length; i++) {
468
					PDEPlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
395
				String libraryName = libraries[i].getName();
469
				} catch (CoreException e) {
396
				if (ClasspathUtilCore.containsVariables(libraryName) && !project.exists(new Path(ClasspathUtilCore.expandLibraryName(libraryName)))) {
397
					for (int j = 0; j < fragments.length; j++) {
398
						importJarFromFragment(project, fragments[j], libraryName);
399
						importSourceFromFragment(project, fragments[j], libraryName, new SubProgressMonitor(monitor, 1));
400
					}
401
				} else {
402
					monitor.worked(1);
403
				}
470
				}
471
				return Status.OK_STATUS;
404
			}
472
			}
405
		}
473
		};
406
		if (markAsBinary) {
474
		buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule());
407
			project.setPersistentProperty(PDECore.EXTERNAL_PROJECT_PROPERTY, PDECore.BINARY_PROJECT_VALUE);
475
		buildJob.schedule();
408
			importAdditionalResources(project, model, new SubProgressMonitor(monitor, 1));
409
		} else {
410
			monitor.done();
411
		}
412
	}
476
	}
413
477
414
	/**
478
	/**
415
	 * Imports the contents of the plugin and imports source files to source folders that will be compiled.
479
	 * Imports the source archives required by the project either by copying or linking, based on the mode
416
	 * @param project destination project of the import
480
	 * constant that is passed to the method (IMPORT_BINARY or IMPORT_BINARY_WITH_LINKS).
417
	 * @param model model representing the plugin to import
481
	 * @param project project destination
482
	 * @param model model we are importing
483
	 * @param mode either IMPORT_BINARY (copies source) or MPORT_BINARY_WITH_LINKS (links source)
418
	 * @param monitor progress monitor
484
	 * @param monitor progress monitor
419
	 * @throws CoreException if there is a problem completing the import
485
	 * @return mapping of library name to the source location
486
	 * @throws CoreException if there are problems importing an archive
420
	 */
487
	 */
421
	private void importAsSource(IProject project, IPluginModelBase model, SubProgressMonitor monitor) throws CoreException {
488
	private Map importSourceArchives(IProject project, IPluginModelBase model, int mode, IProgressMonitor monitor) throws CoreException {
422
		monitor.beginTask("", 4); //$NON-NLS-1$
489
		String[] libraries = getLibraryNames(model);
423
		importAsBinary(project, model, false, new SubProgressMonitor(monitor, 2));
490
		try {
424
		List list = importAdditionalResources(project, model, new SubProgressMonitor(monitor, 1));
491
			monitor.beginTask(PDEUIMessages.ImportWizard_operation_importingSource, libraries.length);
425
		WorkspaceBuildModel buildModel = new WorkspaceBuildModel(project.getFile("build.properties")); //$NON-NLS-1$
492
426
		if (!isJARd(model) || containsCode(new File(model.getInstallLocation()))) {
493
			Map sourceMap = new HashMap(libraries.length);
427
			String[] libraries = getLibraryNames(model, false);
494
			SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
428
			if (libraries.length == 0)
429
				libraries = new String[] {"."}; //$NON-NLS-1$
430
			for (int i = 0; i < libraries.length; i++) {
495
			for (int i = 0; i < libraries.length; i++) {
431
				if (ClasspathUtilCore.containsVariables(libraries[i]))
496
				String zipName = ClasspathUtilCore.getSourceZipName(libraries[i]);
432
					continue;
497
				IPath srcPath = manager.findSourcePath(model.getPluginBase(), new Path(zipName));
433
				String name = ClasspathUtilCore.expandLibraryName(libraries[i]);
498
				if (srcPath != null) {
434
				IPath libraryPath = (name.equals(".") && isJARd(model)) //$NON-NLS-1$
499
					zipName = srcPath.lastSegment();
435
				? new Path(new File(model.getInstallLocation()).getName())
500
					IPath dstPath = new Path(zipName);
436
						: new Path(name);
501
					sourceMap.put(libraries[i], dstPath);
437
				IResource jarFile = project.findMember(libraryPath);
502
					if (project.findMember(dstPath) == null) {
438
				if (jarFile != null) {
503
						if (mode == IMPORT_BINARY) {
439
					String srcName = ClasspathUtilCore.getSourceZipName(libraryPath.lastSegment());
504
							PluginImportHelper.copyArchive(new File(srcPath.toOSString()), project.getFile(dstPath), new SubProgressMonitor(monitor, 1));
440
					IResource srcZip = jarFile.getProject().findMember(srcName);
505
						} else if (mode == IMPORT_BINARY_WITH_LINKS) {
441
					if (srcZip == null) {
506
							IFile dstFile = project.getFile(dstPath);
442
						int extIndex = srcName.lastIndexOf('.');
507
							dstFile.createLink(srcPath, IResource.NONE, new SubProgressMonitor(monitor, 1));
443
						if (extIndex != -1) {
444
							srcZip = jarFile.getProject().findMember(srcName.substring(0, extIndex));
445
						}
446
					}
447
					// srcZip == null if plug-in has embedded source
448
					// if it jarred, all necessary files already in src folder
449
					if (srcZip == null && libraries[i].equals(".") && !isJARd(model)) //$NON-NLS-1$
450
						// if src does not exist (and returns null), then must not be plug-in with embedded source
451
						srcZip = jarFile.getProject().findMember("src"); //$NON-NLS-1$
452
					if (srcZip != null) {
453
						String jarName = libraries[i].equals(".") ? "" : libraryPath.removeFileExtension().lastSegment(); //$NON-NLS-1$ //$NON-NLS-2$
454
						String folder = addBuildEntry(buildModel, "source." + libraries[i], "src" + (jarName.length() == 0 ? "/" : "-" + jarName + "/")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
455
						IFolder dest = jarFile.getProject().getFolder(folder);
456
457
						if (srcZip instanceof IFolder) {
458
							// if the source (srcZip) equals the destination folder (dest), then we don't want to delete/copy since every
459
							// is already where it needs to be.  This happens when importing source bundles in folder format declaring source with ext. point. (bug 214542)
460
							if (!srcZip.equals(dest)) {
461
								if (dest.exists()) {
462
									dest.delete(true, null);
463
								}
464
								((IFolder) srcZip).move(dest.getFullPath(), true, new SubProgressMonitor(monitor, 1));
465
							}
466
						} else if (srcZip instanceof IFile) {
467
							if (!dest.exists()) {
468
								dest.create(true, true, null);
469
							}
470
							extractZipFile(srcZip.getLocation().toFile(), dest.getFullPath(), new SubProgressMonitor(monitor, 1));
471
							srcZip.delete(true, null);
472
						} else
473
							monitor.worked(1);
474
475
						if (jarFile instanceof IFile) {
476
							if (isJARd(model)) {
477
								extractJavaResources(jarFile.getLocation().toFile(), dest, new SubProgressMonitor(monitor, 1));
478
							} else {
479
								extractResources(jarFile.getLocation().toFile(), dest, new SubProgressMonitor(monitor, 1));
480
							}
481
							jarFile.delete(true, null);
482
						} else {
483
							moveBinaryContents((IContainer) jarFile, dest, new SubProgressMonitor(monitor, 1));
484
						}
508
						}
485
					}
509
					}
486
				} else if (name.equals(".") && project.getFolder("src").exists()) { //$NON-NLS-1$ //$NON-NLS-2$
487
					addBuildEntry(buildModel, "source..", "src/"); //$NON-NLS-1$ //$NON-NLS-2$
488
				}
510
				}
489
			}
511
			}
512
			return sourceMap;
513
		} finally {
514
			monitor.done();
490
		}
515
		}
491
		configureBinIncludes(buildModel, model, project);
492
		if (list.size() > 0)
493
			configureSrcIncludes(buildModel, list);
494
		buildModel.save();
495
	}
516
	}
496
517
497
	/**
518
	/**
498
	 * Moves the binary files from the source container to the folder destination.
519
	 * Looks up the source locations for the plug-in and imports the source for each library.  Each source root is
499
	 * Moves any file that isn't a .class file
520
	 * extracted to a source folder in the project and a build model containing the source entries is returned.
500
	 * @param srcFolder container to move from
521
	 * 
501
	 * @param dest folder to move to
522
	 * @param project destination project
523
	 * @param model plug-in being imported
502
	 * @param monitor progress monitor
524
	 * @param monitor progress monitor
525
	 * @return a workspace build model containing entries for each created source folder
526
	 * @throws CoreException if there is a problem extracting the source or creating a build entry
503
	 */
527
	 */
504
	private void moveBinaryContents(IContainer srcFolder, IFolder dest, IProgressMonitor monitor) {
528
	private WorkspaceBuildModel extractSourceFolders(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
505
		try {
529
		try {
506
			// get all the folders for which we want to search
530
			String[] libraries = getLibraryNames(model);
507
			IResource[] children = dest.members();
531
			monitor.beginTask(PDEUIMessages.ImportWizard_operation_importingSource, libraries.length);
508
			ArrayList validFolders = new ArrayList();
509
			for (int i = 0; i < children.length; i++)
510
				if (children[i] instanceof IFolder) {
511
					String folderName = children[i].getName();
512
					IResource folder = srcFolder.findMember(folderName);
513
					if (folder != null && folder instanceof IFolder)
514
						validFolders.add(folder);
515
				}
516
532
517
			monitor.beginTask(new String(), validFolders.size());
533
			WorkspaceBuildModel buildModel = new WorkspaceBuildModel(project.getFile("build.properties")); //$NON-NLS-1$
534
			SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
518
535
519
			ListIterator li = validFolders.listIterator();
536
			// Need to do different things based on whether we have a individual source bundle or the old style separated zips
520
			while (li.hasNext()) {
537
			if (manager.hasBundleManifestLocation(model.getPluginBase())) {
521
				IFolder folder = (IFolder) li.next();
538
				File srcFile = manager.findSourcePlugin(model.getPluginBase());
522
				int pathSegments = folder.getProjectRelativePath().segmentCount() - 1;
539
				Set sourceRoots = manager.findSourceRoots(model.getPluginBase());
523
				Stack stack = new Stack();
540
				for (int i = 0; i < libraries.length; i++) {
524
				IResource[] resources = folder.members();
541
					if (libraries[i].equals(DEFAULT_LIBRARY_NAME)) {
525
				for (int i = 0; i < resources.length; i++)
542
						// Need to pull out any java source that is not in another source root
526
					stack.push(resources[i]);
543
						IResource destination = project.getFolder(DEFAULT_SOURCE_DIR);
527
544
						if (!destination.exists()) {
528
				while (!stack.isEmpty()) {
545
							List excludeFolders = new ArrayList(sourceRoots.size());
529
					IResource res = (IResource) stack.pop();
546
							for (Iterator iterator = sourceRoots.iterator(); iterator.hasNext();) {
530
					if (res instanceof IFile) {
547
								String root = (String) iterator.next();
531
						if (!res.getName().endsWith(".class")) { //$NON-NLS-1$
548
								if (!root.equals(DEFAULT_LIBRARY_NAME)) {
532
							String pathName = res.getProjectRelativePath().removeFirstSegments(pathSegments).toString();
549
									excludeFolders.add(new Path(root));
533
							IFile destFile = dest.getFile(pathName);
550
								}
534
							if (!destFile.getParent().exists()) {
535
								CoreUtility.createFolder((IFolder) destFile.getParent());
536
							}
551
							}
537
							// file might exist if previous project was deleted without removing underlying resources
552
							PluginImportHelper.extractJavaSourceFromArchive(srcFile, excludeFolders, destination.getFullPath(), new SubProgressMonitor(monitor, 1));
538
							if (destFile.exists())
553
							addBuildEntry(buildModel, "source." + DEFAULT_LIBRARY_NAME, DEFAULT_SOURCE_DIR + "/"); //$NON-NLS-1$ //$NON-NLS-2$
539
								destFile.delete(true, null);
554
						}
540
							res.move(destFile.getFullPath(), true, null);
555
					} else if (sourceRoots.contains(getSourceDirName(libraries[i]))) {
556
						IPath sourceDir = new Path(getSourceDirName(libraries[i]));
557
						IResource destination = project.getFolder(sourceDir);
558
						if (!destination.exists()) {
559
							PluginImportHelper.extractFolderFromArchive(srcFile, sourceDir, destination.getFullPath(), new SubProgressMonitor(monitor, 1));
560
							addBuildEntry(buildModel, "source." + libraries[i], sourceDir.toString()); //$NON-NLS-1$
561
						}
562
					}
563
				}
564
			} else {
565
				// Old style, zips in folders, determine the source zip name/location and extract it to the project
566
				for (int i = 0; i < libraries.length; i++) {
567
					String zipName = ClasspathUtilCore.getSourceZipName(libraries[i]);
568
					IPath srcPath = manager.findSourcePath(model.getPluginBase(), new Path(zipName));
569
					if (srcPath != null) {
570
						IPath dstPath = new Path(getSourceDirName(libraries[i]));
571
						IResource destination = project.getFolder(dstPath);
572
						if (!destination.exists()) {
573
							PluginImportHelper.extractArchive(new File(srcPath.toOSString()), destination.getFullPath(), new SubProgressMonitor(monitor, 1));
574
							addBuildEntry(buildModel, "source." + libraries[i], dstPath.toString()); //$NON-NLS-1$
541
						}
575
						}
542
					} else {
543
						resources = ((IFolder) res).members();
544
						for (int i = 0; i < resources.length; i++)
545
							stack.push(resources[i]);
546
					}
576
					}
547
				}
577
				}
548
				folder.delete(true, null);
549
				monitor.worked(1);
550
			}
578
			}
551
		} catch (CoreException e) {
579
			return buildModel;
580
		} finally {
581
			monitor.done();
552
		}
582
		}
553
	}
583
	}
554
584
555
	/**
585
	/**
556
	 * Searches source locations for files to import to the new project, will ignore
586
	 * Extracts any additional files and folders that exist in the source location
557
	 * src.zip.
587
	 * @param project the destination project
558
	 * @param project destination project of the import
588
	 * @param model the plugin being imported
559
	 * @param model model representing the plugin to import
560
	 * @param monitor progress monitor
589
	 * @param monitor progress monitor
561
	 * @return list of imported files
590
	 * @throws CoreException is there is a problem importing the files
562
	 * @throws CoreException if there is a problem completing the import
563
	 */
591
	 */
564
	private List importAdditionalResources(IProject project, IPluginModelBase model, SubProgressMonitor monitor) throws CoreException {
592
	private void importAdditionalSourceFiles(IProject project, IPluginModelBase model, SubProgressMonitor monitor) throws CoreException {
565
		SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
593
		File sourceLocation = PDECore.getDefault().getSourceLocationManager().findSourcePlugin(model.getPluginBase());
566
		File location = manager.findSourcePlugin(model.getPluginBase());
594
		if (sourceLocation != null) {
567
		if (location != null) {
595
			if (sourceLocation.isFile()) {
568
			ArrayList list = new ArrayList();
596
				ArrayList collected = new ArrayList();
569
			if (location.isDirectory()) {
597
				ZipFileStructureProvider provider = null;
570
				Object root = location;
571
				File[] children = location.listFiles();
572
				if (children != null) {
573
					for (int i = 0; i < children.length; i++) {
574
						String name = children[i].getName();
575
						if (!project.exists(new Path(name)) && !"src.zip".equals(name)) { //$NON-NLS-1$
576
							list.add(children[i]);
577
						}
578
					}
579
					importContent(root, project.getFullPath(), FileSystemStructureProvider.INSTANCE, list, monitor);
580
					ArrayList srcEntryList = new ArrayList(list.size());
581
					for (ListIterator iterator = list.listIterator(); iterator.hasNext();) {
582
						File current = (File) iterator.next();
583
						String entry = current.getName();
584
						if (current.isDirectory()) {
585
							entry += "/"; //$NON-NLS-1$
586
						}
587
						srcEntryList.add(entry);
588
					}
589
					return srcEntryList;
590
				}
591
			} else if (location.isFile()) {
592
				ZipFile zipFile = null;
593
				try {
598
				try {
594
					zipFile = new ZipFile(location);
599
					provider = new ZipFileStructureProvider(new ZipFile(sourceLocation));
595
					ZipFileStructureProvider zipProvider = new ZipFileStructureProvider(zipFile);
596
					Object root = zipProvider.getRoot();
597
					collectAdditionalResources(zipProvider, root, list, project);
598
					importContent(root, project.getFullPath(), zipProvider, list, monitor);
599
					ArrayList srcEntryList = new ArrayList(list.size());
600
					for (Iterator iterator = list.iterator(); iterator.hasNext();) {
601
						ZipEntry current = (ZipEntry) iterator.next();
602
						String entry = current.getName();
603
						srcEntryList.add(entry);
604
					}
605
					return srcEntryList;
606
				} catch (IOException e) {
600
				} catch (IOException e) {
607
					IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
601
					IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
608
					throw new CoreException(status);
602
					throw new CoreException(status);
609
				} finally {
610
					if (zipFile != null) {
611
						try {
612
							zipFile.close();
613
						} catch (IOException e) {
614
						}
615
					}
616
				}
603
				}
604
				PluginImportHelper.collectNonJavaFiles(provider, provider.getRoot(), collected);
605
				PluginImportHelper.importContent(provider.getRoot(), project.getFullPath(), provider, collected, monitor);
606
			} else {
607
				// TODO Test how to do directories
608
				ArrayList collected = new ArrayList();
609
				PluginImportHelper.collectNonJavaFiles(FileSystemStructureProvider.INSTANCE, sourceLocation, collected);
610
				PluginImportHelper.importContent(sourceLocation, project.getFullPath(), FileSystemStructureProvider.INSTANCE, collected, monitor);
617
			}
611
			}
618
		}
612
		}
619
		return new ArrayList(0);
613
	}
614
615
	/**
616
	 * Imports files from the plug-in that are necessary to make the created project a plug-in project.
617
	 * Specifically the manifest and related file are extracted.  
618
	 * @param project
619
	 * @param model
620
	 * @param monitor
621
	 * @throws CoreException if there is a problem importing the content
622
	 */
623
	private void importRequiredPluginFiles(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
624
		if (isJARd(model)) {
625
			ArrayList collected = new ArrayList();
626
			ZipFileStructureProvider provider = null;
627
			try {
628
				provider = new ZipFileStructureProvider(new ZipFile(new File(model.getInstallLocation())));
629
			} catch (IOException e) {
630
				IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
631
				throw new CoreException(status);
632
			}
633
			PluginImportHelper.collectRequiredBundleFiles(provider, provider.getRoot(), collected);
634
			PluginImportHelper.importContent(provider.getRoot(), project.getFullPath(), provider, collected, monitor);
635
		} else {
636
			ArrayList collected = new ArrayList();
637
			File file = new File(model.getInstallLocation());
638
			PluginImportHelper.collectRequiredBundleFiles(FileSystemStructureProvider.INSTANCE, file, collected);
639
			PluginImportHelper.importContent(file, project.getFullPath(), FileSystemStructureProvider.INSTANCE, collected, monitor);
640
		}
641
	}
642
643
	private String addBuildEntry(WorkspaceBuildModel model, String key, String value) throws CoreException {
644
		IBuild build = model.getBuild(true);
645
		IBuildEntry entry = build.getEntry(key);
646
		if (entry == null) {
647
			entry = model.getFactory().createEntry(key);
648
			entry.addToken(value);
649
			build.add(entry);
650
		}
651
		String[] tokens = entry.getTokens();
652
		return (tokens.length > 0) ? tokens[0] : "src/"; //$NON-NLS-1$
620
	}
653
	}
621
654
622
	private void configureBinIncludes(WorkspaceBuildModel buildModel, IPluginModelBase model, IProject project) throws CoreException {
655
	private void configureBinIncludes(WorkspaceBuildModel buildModel, IPluginModelBase model, IProject project) throws CoreException {
Lines 640-646 Link Here
640
					entry.addToken(token);
673
					entry.addToken(token);
641
				}
674
				}
642
			} else {
675
			} else {
643
				String[] tokens = getTopLevelResources(location);
676
				String[] tokens = PluginImportHelper.getTopLevelResources(location);
644
				for (int i = 0; i < tokens.length; i++) {
677
				for (int i = 0; i < tokens.length; i++) {
645
					IResource res = project.findMember(tokens[i]);
678
					IResource res = project.findMember(tokens[i]);
646
					if ((res == null) && (build.getEntry(IBuildEntry.JAR_PREFIX + tokens[i]) == null))
679
					if ((res == null) && (build.getEntry(IBuildEntry.JAR_PREFIX + tokens[i]) == null))
Lines 670-882 Link Here
670
		return set;
703
		return set;
671
	}
704
	}
672
705
673
	private void configureSrcIncludes(WorkspaceBuildModel buildModel, List list) throws CoreException {
674
		IBuildEntry entry = buildModel.getBuild(true).getEntry("src.includes"); //$NON-NLS-1$
675
		if (entry == null) {
676
			entry = buildModel.getFactory().createEntry("src.includes"); //$NON-NLS-1$
677
			for (int i = 0; i < list.size(); i++) {
678
				entry.addToken(list.get(i).toString());
679
			}
680
			buildModel.getBuild().add(entry);
681
		}
682
	}
683
684
	private String addBuildEntry(WorkspaceBuildModel model, String key, String value) throws CoreException {
685
		IBuild build = model.getBuild(true);
686
		IBuildEntry entry = build.getEntry(key);
687
		if (entry == null) {
688
			entry = model.getFactory().createEntry(key);
689
			entry.addToken(value);
690
			build.add(entry);
691
		}
692
		String[] tokens = entry.getTokens();
693
		return (tokens.length > 0) ? tokens[0] : "src/"; //$NON-NLS-1$
694
	}
695
696
	/**
697
	 * Creates links in the project to the source locations for the various libraries.
698
	 * If the source for all libraries is in a single bundle, one link is created
699
	 * @param project destination project of the import
700
	 * @param model model representing the plugin to import
701
	 * @param monitor progress monitor
702
	 * @throws CoreException if there is a problem completing the import
703
	 */
704
	private void linkSourceArchives(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
705
		String[] libraries = getLibraryNames(model, true);
706
		monitor.beginTask(PDEUIMessages.ImportWizard_operation_copyingSource, libraries.length);
707
708
		SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
709
		if (manager.hasBundleManifestLocation(model.getPluginBase())) {
710
			IPath srcPath = manager.findSourcePath(model.getPluginBase(), null);
711
			if (srcPath != null) {
712
				// Source for all libraries is in the same bundle, just create one link to the source bundle
713
				IPath path = new Path(project.getName() + "src.zip"); //$NON-NLS-1$
714
				IFile srcFile = project.getFile(path.lastSegment());
715
				if (!srcFile.exists()) {
716
					srcFile.createLink(srcPath, IResource.NONE, new SubProgressMonitor(monitor, 1));
717
				}
718
			}
719
			monitor.worked(libraries.length);
720
		} else {
721
			for (int i = 0; i < libraries.length; i++) {
722
				String zipName = ClasspathUtilCore.getSourceZipName(libraries[i]);
723
				IPath path = new Path(zipName);
724
				if (project.findMember(path) == null) {
725
					IPath srcPath = manager.findSourcePath(model.getPluginBase(), path);
726
					if (srcPath != null) {
727
						if ("src.zip".equals(zipName) && isJARd(model)) { //$NON-NLS-1$
728
							path = new Path(ClasspathUtilCore.getSourceZipName(new File(model.getInstallLocation()).getName()));
729
						}
730
						IFile zipFile = project.getFile(path.lastSegment());
731
						if (!zipFile.exists()) {
732
							zipFile.createLink(srcPath, IResource.NONE, new SubProgressMonitor(monitor, 1));
733
						}
734
					}
735
				}
736
				monitor.worked(1);
737
			}
738
		}
739
		monitor.done();
740
	}
741
742
	private void importSourceArchives(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
743
		String[] libraries = getLibraryNames(model, true);
744
		monitor.beginTask(PDEUIMessages.ImportWizard_operation_copyingSource, libraries.length);
745
746
		SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
747
748
		Set roots = null;
749
		if (manager.hasBundleManifestLocation(model.getPluginBase()))
750
			roots = manager.findSourceRoots(model.getPluginBase());
751
752
		for (int i = 0; i < libraries.length; i++) {
753
			String zipName = ClasspathUtilCore.getSourceZipName(libraries[i]);
754
			IPath path = new Path(zipName);
755
			if (project.findMember(path) == null) {
756
				// if we are importing the source through a sourceBundle header...
757
				if (roots != null) {
758
					IPath sourceLocation = manager.findSourcePath(model.getPluginBase(), null);
759
					String currentRoot = ".".equals(libraries[i]) ? "." : path.removeFileExtension().toString(); //$NON-NLS-1$ //$NON-NLS-2$
760
					if (roots.contains(currentRoot)) {
761
						if (".".equals(currentRoot)) { //$NON-NLS-1$
762
							// Save to a special folder name based on the install location
763
							IPath sourceName = getDefaultSourceNameForProject(model);
764
							sourceName = sourceName.removeFileExtension();
765
							IFolder dest = project.getFolder(sourceName);
766
							if (!dest.exists()) {
767
								dest.create(true, true, null);
768
							}
769
770
							// List all of the other source roots so they are not included when importing source from the root, ".", of the jar
771
							Set allBundleRoots = manager.findAllSourceRootsInSourceLocation(model.getPluginBase());
772
							List rootsToExclude = new ArrayList(allBundleRoots.size() - 1);
773
							for (Iterator iterator2 = allBundleRoots.iterator(); iterator2.hasNext();) {
774
								String rootString = (String) iterator2.next();
775
								if (!".".equals(rootString)) { //$NON-NLS-1$
776
									rootsToExclude.add(new Path(rootString));
777
								}
778
							}
779
780
							// Extract folders containing java source
781
							extractJavaSource(new File(sourceLocation.toOSString()), rootsToExclude, dest, monitor);
782
						} else {
783
							// Extract the specific library from it's folder
784
							extractResourcesFromFolder(new File(sourceLocation.toOSString()), new Path(currentRoot), project, monitor);
785
						}
786
					}
787
				} else {
788
					IPath srcPath = manager.findSourcePath(model.getPluginBase(), path);
789
					if (srcPath != null) {
790
						if ("src.zip".equals(zipName) && isJARd(model)) { //$NON-NLS-1$
791
							path = getDefaultSourceNameForProject(model);
792
						}
793
						importArchive(project, new File(srcPath.toOSString()), path);
794
					}
795
				}
796
			}
797
			monitor.worked(1);
798
		}
799
		monitor.done();
800
	}
801
802
	/**
706
	/**
803
	 * Creates a path representing a zip file that is named based on the plugin install location.
707
	 * Creates a model for an existing manifest file, replacing the classpath entry with the
804
	 * Used to replace src.zip with a more unique and meaningful name.
708
	 * new location of the referenced library.  Also removes any extra entries such as signing
805
	 * @param model model that the src.zip containg source for
709
	 * headers. 
806
	 * @return a new path describing the zip file
710
	 * @param project
711
	 * @param base
807
	 */
712
	 */
808
	private IPath getDefaultSourceNameForProject(IPluginModelBase model) {
809
		return new Path(ClasspathUtilCore.getSourceZipName(new File(model.getInstallLocation()).getName()));
810
	}
811
812
	private String[] getLibraryNames(IPluginModelBase model, boolean expand) {
813
		IPluginLibrary[] libraries = model.getPluginBase().getLibraries();
814
		ArrayList list = new ArrayList();
815
		for (int i = 0; i < libraries.length; i++) {
816
			if (expand)
817
				list.add(ClasspathUtilCore.expandLibraryName(libraries[i].getName()));
818
			else
819
				list.add(libraries[i].getName());
820
		}
821
		if (libraries.length == 0 && isJARd(model))
822
			list.add("."); //$NON-NLS-1$
823
		return (String[]) list.toArray(new String[list.size()]);
824
	}
825
826
	private void extractJARdPlugin(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
827
		ZipFile zipFile = null;
828
		try {
829
			zipFile = new ZipFile(model.getInstallLocation());
830
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
831
			if (!containsCode(provider)) {
832
				extractZipFile(new File(model.getInstallLocation()), project.getFullPath(), monitor);
833
				return;
834
			}
835
			ArrayList collected = new ArrayList();
836
			collectNonJavaResources(provider, provider.getRoot(), collected);
837
			importContent(provider.getRoot(), project.getFullPath(), provider, collected, monitor);
838
839
			File file = new File(model.getInstallLocation());
840
			if (hasEmbeddedSource(provider) && fImportType == IMPORT_WITH_SOURCE) {
841
				collected = new ArrayList();
842
				collectJavaFiles(provider, provider.getRoot(), collected);
843
				importContent(provider.getRoot(), project.getFullPath(), provider, collected, monitor);
844
				collected = new ArrayList();
845
				collectJavaResources(provider, provider.getRoot(), collected);
846
				importContent(provider.getRoot(), project.getFullPath().append("src"), provider, collected, monitor); //$NON-NLS-1$
847
			} else {
848
				if (fImportType == IMPORT_BINARY_WITH_LINKS) {
849
					project.getFile(file.getName()).createLink(new Path(file.getAbsolutePath()), IResource.NONE, null);
850
				} else {
851
					importArchive(project, file, new Path(file.getName()));
852
				}
853
				if (!hasEmbeddedSource(provider)) {
854
					if (fImportType == IMPORT_BINARY_WITH_LINKS) {
855
						linkSourceArchives(project, model, new SubProgressMonitor(monitor, 1));
856
					} else {
857
						importSourceArchives(project, model, new SubProgressMonitor(monitor, 1));
858
					}
859
				}
860
			}
861
			if (fImportType != IMPORT_WITH_SOURCE) {
862
				modifyBundleClasspathHeader(project, model);
863
			} else {
864
				removeSignedHeaders(project);
865
			}
866
			setPermissions(model, project);
867
		} catch (IOException e) {
868
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
869
			throw new CoreException(status);
870
		} finally {
871
			if (zipFile != null) {
872
				try {
873
					zipFile.close();
874
				} catch (IOException e) {
875
				}
876
			}
877
		}
878
	}
879
880
	private void modifyBundleClasspathHeader(IProject project, IPluginModelBase base) {
713
	private void modifyBundleClasspathHeader(IProject project, IPluginModelBase base) {
881
		IFile file = project.getFile(JarFile.MANIFEST_NAME);
714
		IFile file = project.getFile(JarFile.MANIFEST_NAME);
882
		if (file.exists()) {
715
		if (file.exists()) {
Lines 908-959 Link Here
908
		}
741
		}
909
	}
742
	}
910
743
911
	private void removeSignedHeaders(IProject project) {
912
		IFile file = project.getFile(JarFile.MANIFEST_NAME);
913
		if (!file.exists())
914
			return;
915
		WorkspaceBundleModel model = new WorkspaceBundleModel(file);
916
		model.save();
917
	}
918
919
	private IProject findProject(String id) {
920
		IPluginModelBase model = PluginRegistry.findModel(id);
921
		if (model != null) {
922
			IResource resource = model.getUnderlyingResource();
923
			if (resource != null)
924
				return resource.getProject();
925
		}
926
		return PDEPlugin.getWorkspace().getRoot().getProject(id);
927
	}
928
929
	private boolean queryReplace(IProject project) throws OperationCanceledException {
930
		switch (fReplaceQuery.doQuery(NLS.bind(PDEUIMessages.ImportWizard_messages_exists, project.getName()))) {
931
			case IImportQuery.CANCEL :
932
				throw new OperationCanceledException();
933
			case IImportQuery.NO :
934
				return false;
935
		}
936
		return true;
937
	}
938
939
	private boolean queryExecutionEnvironment(String message) throws OperationCanceledException {
940
		switch (fExecutionQuery.doQuery(message)) {
941
			case IImportQuery.CANCEL :
942
				throw new OperationCanceledException();
943
			case IImportQuery.NO :
944
				return false;
945
		}
946
		return true;
947
	}
948
949
	private void setProjectDescription(IProject project, IPluginModelBase model) throws CoreException {
950
		IProjectDescription desc = project.getDescription();
951
		if (!desc.hasNature(PDE.PLUGIN_NATURE))
952
			CoreUtility.addNatureToProject(project, PDE.PLUGIN_NATURE, null);
953
		if (needsJavaNature(project, model) && !desc.hasNature(JavaCore.NATURE_ID))
954
			CoreUtility.addNatureToProject(project, JavaCore.NATURE_ID, null);
955
	}
956
957
	private boolean needsJavaNature(IProject project, IPluginModelBase model) {
744
	private boolean needsJavaNature(IProject project, IPluginModelBase model) {
958
		if (model.getPluginBase().getLibraries().length > 0)
745
		if (model.getPluginBase().getLibraries().length > 0)
959
			return true;
746
			return true;
Lines 970-1100 Link Here
970
		return false;
757
		return false;
971
	}
758
	}
972
759
973
	private boolean isExempt(IPluginModelBase model) {
760
	private void setProjectNatures(IProject project, IPluginModelBase model) throws CoreException {
974
		String id = model.getPluginBase().getId();
761
		IProjectDescription desc = project.getDescription();
975
		if ("org.apache.ant".equals(id) //$NON-NLS-1$
762
		if (!desc.hasNature(PDE.PLUGIN_NATURE))
976
				|| "org.eclipse.osgi.util".equals(id) //$NON-NLS-1$
763
			CoreUtility.addNatureToProject(project, PDE.PLUGIN_NATURE, null);
977
				|| "org.eclipse.osgi.services".equals(id) //$NON-NLS-1$
764
		if (needsJavaNature(project, model) && !desc.hasNature(JavaCore.NATURE_ID))
978
				|| "org.eclipse.core.runtime.compatibility.registry".equals(id)) //$NON-NLS-1$
765
			CoreUtility.addNatureToProject(project, JavaCore.NATURE_ID, null);
979
			return true;
980
981
		if ("org.eclipse.swt".equals(id) && !isJARd(model)) //$NON-NLS-1$
982
			return true;
983
		return false;
984
	}
985
986
	private boolean isJARd(IPluginModelBase model) {
987
		return new File(model.getInstallLocation()).isFile();
988
	}
989
990
	private void setPermissions(IPluginModelBase model, IProject project) {
991
		try {
992
			if (!Platform.getOS().equals(Constants.OS_WIN32) && model instanceof IFragmentModel) {
993
				IFragment fragment = ((IFragmentModel) model).getFragment();
994
				if ("org.eclipse.swt".equals(fragment.getPluginId())) { //$NON-NLS-1$
995
					IResource[] children = project.members();
996
					for (int i = 0; i < children.length; i++) {
997
						if (children[i] instanceof IFile && isInterestingResource(children[i].getName())) {
998
							Runtime.getRuntime().exec(new String[] {"chmod", "755", children[i].getLocation().toOSString()}).waitFor(); //$NON-NLS-1$ //$NON-NLS-2$
999
						}
1000
					}
1001
				}
1002
			}
1003
		} catch (CoreException e) {
1004
		} catch (InterruptedException e) {
1005
		} catch (IOException e) {
1006
		}
1007
	}
1008
1009
	private boolean isInterestingResource(String name) {
1010
		return name.endsWith(".jnilib") //$NON-NLS-1$
1011
				|| name.endsWith(".sl") //$NON-NLS-1$
1012
				|| name.endsWith(".a") //$NON-NLS-1$
1013
				|| name.indexOf(".so") != -1; //$NON-NLS-1$
1014
	}
1015
1016
	private IFragment[] getFragmentsFor(IPluginModelBase model) {
1017
		ArrayList result = new ArrayList();
1018
		for (int i = 0; i < fModels.length; i++) {
1019
			if (fModels[i] instanceof IFragmentModel) {
1020
				HostSpecification spec = fModels[i].getBundleDescription().getHost();
1021
				BundleDescription host = spec == null ? null : (BundleDescription) spec.getSupplier();
1022
				if (model.getBundleDescription().equals(host)) {
1023
					result.add(((IFragmentModel) fModels[i]).getFragment());
1024
				}
1025
			}
1026
		}
1027
		return (IFragment[]) result.toArray(new IFragment[result.size()]);
1028
	}
1029
1030
	private void importJarFromFragment(IProject project, IFragment fragment, String name) throws CoreException {
1031
		IPath jarPath = new Path(ClasspathUtilCore.expandLibraryName(name));
1032
		File jar = new File(fragment.getModel().getInstallLocation(), jarPath.toString());
1033
		if (jar.exists()) {
1034
			importArchive(project, jar, jarPath);
1035
		}
1036
	}
766
	}
1037
767
1038
	/**
768
	/**
1039
	 * Imports the source for a library from a fragment.
769
	 * Gets the list of libraries from the model and returns an array of their expanded
1040
	 * @param project destination project of the import
770
	 * names.  Will add the default library name if no libraries are specified.
1041
	 * @param fragment fragment to import the library from
771
	 * @param model
1042
	 * @param libraryName name of the library to import, 
772
	 * @return list of library names
1043
	 * @param monitor progress monitor
1044
	 * @throws CoreException if there is a problem completing the import
1045
	 */
773
	 */
1046
	private void importSourceFromFragment(IProject project, IFragment fragment, String libraryName, IProgressMonitor monitor) throws CoreException {
774
	private String[] getLibraryNames(IPluginModelBase model) {
1047
		try {
775
		IPluginLibrary[] libraries = model.getPluginBase().getLibraries();
1048
			IPath jarPath = new Path(ClasspathUtilCore.expandLibraryName(libraryName));
776
		ArrayList list = new ArrayList();
1049
			String zipName = ClasspathUtilCore.getSourceZipName(jarPath.toString());
777
		for (int i = 0; i < libraries.length; i++) {
1050
			IPath path = new Path(zipName);
778
			list.add(ClasspathUtilCore.expandLibraryName(libraries[i].getName()));
1051
			if (project.findMember(path) == null) {
1052
				SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
1053
				IPath srcPath = manager.findSourcePath(fragment, path);
1054
				if (srcPath != null) {
1055
					if (manager.hasBundleManifestLocation(fragment)) {
1056
						// Extract the specific library from it's folder
1057
						extractResourcesFromFolder(new File(srcPath.toOSString()), path.removeFileExtension(), project, monitor);
1058
					} else {
1059
						importArchive(project, new File(srcPath.toOSString()), path);
1060
					}
1061
				}
1062
			}
1063
		} finally {
1064
			monitor.done();
1065
		}
1066
	}
1067
1068
	protected void collectAdditionalResources(ZipFileStructureProvider provider, Object element, ArrayList collected, IProject project) {
1069
		collectAdditionalResources(provider, element, collected);
1070
		ListIterator li = collected.listIterator();
1071
		while (li.hasNext()) {
1072
			ZipEntry ze = (ZipEntry) li.next();
1073
			String name = ze.getName();
1074
			// only import the entries that don't already exist
1075
			if (project.findMember(name) != null) {
1076
				li.remove();
1077
			}
1078
		}
779
		}
780
		if (libraries.length == 0 && isJARd(model))
781
			list.add(DEFAULT_LIBRARY_NAME);
782
		return (String[]) list.toArray(new String[list.size()]);
1079
	}
783
	}
1080
784
1081
	protected void collectNonJavaResources(ZipFileStructureProvider provider, Object element, ArrayList collected) {
785
	/**
1082
		super.collectNonJavaResources(provider, element, collected);
786
	 * Returns the standard source directory name for a library name.  
1083
		if (fImportType != IMPORT_WITH_SOURCE)
787
	 * Used to get the source root name for a library as well as the
1084
			return;
788
	 * standard destination name.
1085
		// filter the resources we get back to include only relevant resource files
789
	 * @param libraryName
1086
		ListIterator li = collected.listIterator();
790
	 * @return source dir name
1087
		while (li.hasNext()) {
791
	 */
1088
			ZipEntry ze = (ZipEntry) li.next();
792
	private String getSourceDirName(String libraryName) {
1089
			String name = ze.getName();
793
		int dot = libraryName.lastIndexOf('.');
1090
			// filter out signature files - bug 175756
794
		return (dot != -1) ? libraryName.substring(0, dot) + DEFAULT_SOURCE_DIR : libraryName;
1091
			if (name.startsWith("META-INF/") && (name.endsWith(".RSA") || name.endsWith(".DSA") || name.endsWith(".SF"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
1092
				li.remove();
1093
		}
1094
	}
795
	}
1095
796
1096
	public void setLaunchedConfiguration(boolean launchedConfiguration) {
797
	/**
1097
		fLaunchedConfigurations = launchedConfiguration;
798
	 * Returns whether the install location of the plug-in is a jar file or a folder
799
	 * @param model
800
	 * @return true if the install location is a jar, false if it is a folder
801
	 */
802
	private boolean isJARd(IPluginModelBase model) {
803
		return new File(model.getInstallLocation()).isFile();
1098
	}
804
	}
1099
805
1100
}
806
}
(-)src/org/eclipse/pde/internal/ui/wizards/imports/PluginImportWizardDetailedPage.java (-15 / +66 lines)
Lines 21-30 Link Here
21
import org.eclipse.jface.dialogs.IDialogSettings;
21
import org.eclipse.jface.dialogs.IDialogSettings;
22
import org.eclipse.jface.layout.GridLayoutFactory;
22
import org.eclipse.jface.layout.GridLayoutFactory;
23
import org.eclipse.jface.viewers.*;
23
import org.eclipse.jface.viewers.*;
24
import org.eclipse.osgi.service.resolver.BundleDescription;
24
import org.eclipse.osgi.util.NLS;
25
import org.eclipse.osgi.util.NLS;
25
import org.eclipse.pde.core.plugin.IPluginModelBase;
26
import org.eclipse.pde.core.plugin.IPluginModelBase;
26
import org.eclipse.pde.internal.core.PDECore;
27
import org.eclipse.pde.internal.core.*;
27
import org.eclipse.pde.internal.core.WorkspaceModelManager;
28
import org.eclipse.pde.internal.core.plugin.AbstractPluginModelBase;
28
import org.eclipse.pde.internal.core.plugin.AbstractPluginModelBase;
29
import org.eclipse.pde.internal.core.util.PatternConstructor;
29
import org.eclipse.pde.internal.core.util.PatternConstructor;
30
import org.eclipse.pde.internal.ui.*;
30
import org.eclipse.pde.internal.ui.*;
Lines 53-59 Link Here
53
	private TableViewer fAvailableListViewer;
53
	private TableViewer fAvailableListViewer;
54
	private Text fFilterText;
54
	private Text fFilterText;
55
	private VersionFilter fVersionFilter;
55
	private VersionFilter fVersionFilter;
56
	private AvailableFilter fFilter;
56
	private AvailableFilter fAvailableFilter;
57
	private SourcePluginFilter fSourceFilter;
57
	// fSelected is used to track the selection in a hash set so we can efficiently
58
	// fSelected is used to track the selection in a hash set so we can efficiently
58
	// filter selected items out of the available item list
59
	// filter selected items out of the available item list
59
	private Set fSelected;
60
	private Set fSelected;
Lines 65-72 Link Here
65
	private Button fRemoveAllButton;
66
	private Button fRemoveAllButton;
66
	private Button fAddRequiredButton;
67
	private Button fAddRequiredButton;
67
	private Button fFilterOldVersionButton;
68
	private Button fFilterOldVersionButton;
69
	private Button fFilterSourcePluginsButton;
68
70
69
	private static final String SETTINGS_SHOW_LATEST = "showLatestPluginsOnly"; //$NON-NLS-1$
71
	private static final String SETTINGS_SHOW_LATEST = "showLatestPluginsOnly"; //$NON-NLS-1$
72
	private static final String SETTINGS_SHOW_SOURCE = "showSourcePlugins"; //$NON-NLS-1$
70
73
71
	private class AvailableFilter extends ViewerFilter {
74
	private class AvailableFilter extends ViewerFilter {
72
		private Pattern fPattern;
75
		private Pattern fPattern;
Lines 131-137 Link Here
131
				return true;
134
				return true;
132
			return hVersion.equals(plugin.getBundleDescription().getVersion());
135
			return hVersion.equals(plugin.getBundleDescription().getVersion());
133
		}
136
		}
137
	}
134
138
139
	/**
140
	 * This filter is used to remove source plug-ins from view
141
	 * 
142
	 */
143
	private class SourcePluginFilter extends ViewerFilter {
144
		/* (non-Javadoc)
145
		 * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
146
		 */
147
		public boolean select(Viewer viewer, Object parentElement, Object element) {
148
			if (element instanceof IPluginModelBase) {
149
				PDEState state = fPage1.getState();
150
				if (state != null) {
151
					BundleDescription description = ((IPluginModelBase) element).getBundleDescription();
152
					if (description != null) {
153
						return state.getBundleSourceEntry(description.getBundleId()) == null;
154
					}
155
				}
156
			}
157
			return true;
158
		}
135
	}
159
	}
136
160
137
	public PluginImportWizardDetailedPage(String pageName, PluginImportWizardFirstPage firstPage) {
161
	public PluginImportWizardDetailedPage(String pageName, PluginImportWizardFirstPage firstPage) {
Lines 160-169 Link Here
160
		Composite buttonContainer = new Composite(container, SWT.NONE);
184
		Composite buttonContainer = new Composite(container, SWT.NONE);
161
		buttonContainer.setLayout(GridLayoutFactory.fillDefaults().create());
185
		buttonContainer.setLayout(GridLayoutFactory.fillDefaults().create());
162
		createComputationsOption(buttonContainer, 3);
186
		createComputationsOption(buttonContainer, 3);
163
		createFilterOption(buttonContainer, 3);
187
		createFilterOptions(buttonContainer, 3);
164
188
165
		addViewerListeners();
189
		addViewerListeners();
166
		addFilter();
190
		addFilters();
167
191
168
		initialize();
192
		initialize();
169
		setControl(container);
193
		setControl(container);
Lines 171-177 Link Here
171
		PlatformUI.getWorkbench().getHelpSystem().setHelp(container, IHelpContextIds.PLUGIN_IMPORT_SECOND_PAGE);
195
		PlatformUI.getWorkbench().getHelpSystem().setHelp(container, IHelpContextIds.PLUGIN_IMPORT_SECOND_PAGE);
172
	}
196
	}
173
197
174
	private void createFilterOption(Composite container, int span) {
198
	private void createFilterOptions(Composite container, int span) {
175
		Composite parent = new Composite(container, SWT.NONE);
199
		Composite parent = new Composite(container, SWT.NONE);
176
		parent.setLayout(GridLayoutFactory.swtDefaults().margins(5, 0).create());
200
		parent.setLayout(GridLayoutFactory.swtDefaults().margins(5, 0).create());
177
		fFilterOldVersionButton = new Button(parent, SWT.CHECK);
201
		fFilterOldVersionButton = new Button(parent, SWT.CHECK);
Lines 188-211 Link Here
188
212
189
		fFilterOldVersionButton.addSelectionListener(new SelectionAdapter() {
213
		fFilterOldVersionButton.addSelectionListener(new SelectionAdapter() {
190
			public void widgetSelected(SelectionEvent e) {
214
			public void widgetSelected(SelectionEvent e) {
191
				fAvailableListViewer.removeFilter(fVersionFilter);
192
				if (fFilterOldVersionButton.getSelection()) {
215
				if (fFilterOldVersionButton.getSelection()) {
193
					fAvailableListViewer.addFilter(fVersionFilter);
216
					fAvailableListViewer.addFilter(fVersionFilter);
217
				} else {
218
					fAvailableListViewer.removeFilter(fVersionFilter);
194
				}
219
				}
195
				fAvailableListViewer.getTable().setRedraw(false);
196
				fAvailableListViewer.refresh();
197
				fAvailableListViewer.getTable().setRedraw(true);
198
			}
220
			}
221
		});
199
222
223
		fFilterSourcePluginsButton = new Button(parent, SWT.CHECK);
224
		// TODO NLS this string, not done so related patches won't conflict
225
		fFilterSourcePluginsButton.setText("Show source plug-ins");
226
		gData = new GridData(GridData.FILL_HORIZONTAL);
227
		gData.horizontalSpan = span;
228
		fFilterSourcePluginsButton.setLayoutData(gData);
229
230
		if (getDialogSettings().get(SETTINGS_SHOW_SOURCE) != null) {
231
			fFilterSourcePluginsButton.setSelection(getDialogSettings().getBoolean(SETTINGS_SHOW_SOURCE));
232
		} else {
233
			fFilterSourcePluginsButton.setSelection(false);
234
		}
235
236
		fFilterSourcePluginsButton.addSelectionListener(new SelectionAdapter() {
237
			public void widgetSelected(SelectionEvent e) {
238
				if (fFilterSourcePluginsButton.getSelection()) {
239
					fAvailableListViewer.removeFilter(fSourceFilter);
240
				} else {
241
					fAvailableListViewer.addFilter(fSourceFilter);
242
				}
243
			}
200
		});
244
		});
201
	}
245
	}
202
246
203
	private void addFilter() {
247
	private void addFilters() {
204
		fVersionFilter = new VersionFilter();
248
		fVersionFilter = new VersionFilter();
205
		fVersionFilter.setModel(fModels);
249
		fVersionFilter.setModel(fModels);
206
		fFilter = new AvailableFilter();
250
		fAvailableFilter = new AvailableFilter();
207
		fAvailableListViewer.addFilter(fFilter);
251
		fSourceFilter = new SourcePluginFilter();
252
		fAvailableListViewer.addFilter(fAvailableFilter);
208
		fAvailableListViewer.addFilter(fVersionFilter);
253
		fAvailableListViewer.addFilter(fVersionFilter);
254
		if (!fFilterSourcePluginsButton.getSelection()) {
255
			fAvailableListViewer.addFilter(fSourceFilter);
256
		}
257
209
		fFilterJob = new WorkbenchJob("FilterJob") { //$NON-NLS-1$
258
		fFilterJob = new WorkbenchJob("FilterJob") { //$NON-NLS-1$
210
			public IStatus runInUIThread(IProgressMonitor monitor) {
259
			public IStatus runInUIThread(IProgressMonitor monitor) {
211
				handleFilter();
260
				handleFilter();
Lines 416-422 Link Here
416
	protected void refreshPage() {
465
	protected void refreshPage() {
417
		fImportListViewer.getTable().removeAll();
466
		fImportListViewer.getTable().removeAll();
418
		fSelected.clear();
467
		fSelected.clear();
419
		fFilter.setPattern("*"); //$NON-NLS-1$
468
		fAvailableFilter.setPattern("*"); //$NON-NLS-1$
420
		fVersionFilter.setModel(fModels);
469
		fVersionFilter.setModel(fModels);
421
		fAvailableListViewer.refresh();
470
		fAvailableListViewer.refresh();
422
		pageChanged();
471
		pageChanged();
Lines 487-494 Link Here
487
		String newFilter;
536
		String newFilter;
488
		if (fFilterText == null || (newFilter = fFilterText.getText().trim()).length() == 0)
537
		if (fFilterText == null || (newFilter = fFilterText.getText().trim()).length() == 0)
489
			newFilter = "*"; //$NON-NLS-1$
538
			newFilter = "*"; //$NON-NLS-1$
490
		changed = fFilter.setPattern(newFilter);
539
		changed = fAvailableFilter.setPattern(newFilter);
491
		if (changed) {
540
		if (changed) {
541
			// TODO Test whether we need to redraw/refresh
492
			fAvailableListViewer.getTable().setRedraw(false);
542
			fAvailableListViewer.getTable().setRedraw(false);
493
			fAvailableListViewer.refresh();
543
			fAvailableListViewer.refresh();
494
			fAvailableListViewer.getTable().setRedraw(true);
544
			fAvailableListViewer.getTable().setRedraw(true);
Lines 632-637 Link Here
632
	public void storeSettings() {
682
	public void storeSettings() {
633
		IDialogSettings settings = getDialogSettings();
683
		IDialogSettings settings = getDialogSettings();
634
		settings.put(SETTINGS_SHOW_LATEST, fFilterOldVersionButton.getSelection());
684
		settings.put(SETTINGS_SHOW_LATEST, fFilterOldVersionButton.getSelection());
685
		settings.put(SETTINGS_SHOW_SOURCE, fFilterSourcePluginsButton.getSelection());
635
		super.storeSettings();
686
		super.storeSettings();
636
	}
687
	}
637
688
(-)src/org/eclipse/pde/internal/ui/wizards/imports/JarImportOperation.java (-479 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.pde.internal.ui.wizards.imports;
12
13
import java.io.*;
14
import java.lang.reflect.InvocationTargetException;
15
import java.util.*;
16
import java.util.zip.ZipFile;
17
import org.eclipse.core.resources.*;
18
import org.eclipse.core.runtime.*;
19
import org.eclipse.pde.internal.core.util.CoreUtility;
20
import org.eclipse.pde.internal.ui.PDEPlugin;
21
import org.eclipse.ui.dialogs.IOverwriteQuery;
22
import org.eclipse.ui.wizards.datatransfer.*;
23
24
public abstract class JarImportOperation implements IWorkspaceRunnable {
25
26
	protected void extractZipFile(File file, IPath destPath, IProgressMonitor monitor) throws CoreException {
27
		ZipFile zipFile = null;
28
		try {
29
			zipFile = new ZipFile(file);
30
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
31
			importContent(provider.getRoot(), destPath, provider, null, monitor);
32
		} catch (IOException e) {
33
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
34
			throw new CoreException(status);
35
		} finally {
36
			if (zipFile != null) {
37
				try {
38
					zipFile.close();
39
				} catch (IOException e) {
40
				}
41
			}
42
		}
43
	}
44
45
	protected void importContent(Object source, IPath destPath, IImportStructureProvider provider, List filesToImport, IProgressMonitor monitor) throws CoreException {
46
		IOverwriteQuery query = new IOverwriteQuery() {
47
			public String queryOverwrite(String file) {
48
				return ALL;
49
			}
50
		};
51
		try {
52
			ImportOperation op = new ImportOperation(destPath, source, provider, query);
53
			op.setCreateContainerStructure(false);
54
			if (filesToImport != null) {
55
				op.setFilesToImport(filesToImport);
56
			}
57
			op.run(monitor);
58
		} catch (InvocationTargetException e) {
59
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
60
			throw new CoreException(status);
61
		} catch (InterruptedException e) {
62
			throw new OperationCanceledException(e.getMessage());
63
		}
64
	}
65
66
	protected void extractResources(File file, IResource dest, IProgressMonitor monitor) throws CoreException {
67
		ZipFile zipFile = null;
68
		try {
69
			zipFile = new ZipFile(file);
70
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
71
			ArrayList collected = new ArrayList();
72
			collectResources(provider, provider.getRoot(), true, collected);
73
			importContent(provider.getRoot(), dest.getFullPath(), provider, collected, monitor);
74
		} catch (IOException e) {
75
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
76
			throw new CoreException(status);
77
		} finally {
78
			if (zipFile != null) {
79
				try {
80
					zipFile.close();
81
				} catch (IOException e) {
82
				}
83
			}
84
		}
85
	}
86
87
	/**
88
	 * Extracts all of the files and subfolders from a single folder within an archive file.
89
	 * @param file archive file to search for files
90
	 * @param folderPath path to the folder to extract from
91
	 * @param dest destination to import content to
92
	 * @param monitor progress monitor
93
	 * @throws CoreException if a problem occurs while extracting
94
	 * @since 3.4
95
	 */
96
	protected void extractResourcesFromFolder(File file, IPath folderPath, IResource dest, IProgressMonitor monitor) throws CoreException {
97
		ZipFile zipFile = null;
98
		try {
99
			zipFile = new ZipFile(file);
100
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
101
			ArrayList collected = new ArrayList();
102
			collectResourcesFromFolder(provider, provider.getRoot(), folderPath, collected);
103
			importContent(provider.getRoot(), dest.getFullPath(), provider, collected, monitor);
104
		} catch (IOException e) {
105
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
106
			throw new CoreException(status);
107
		} finally {
108
			if (zipFile != null) {
109
				try {
110
					zipFile.close();
111
				} catch (IOException e) {
112
				}
113
			}
114
		}
115
	}
116
117
	/**
118
	 * Searches the given archive file for java source folders.  Imports the files in the
119
	 * source folders to the specified destination unless the folder is in the list of 
120
	 * folders to exclude. 
121
	 * @param file archive file to search for source in
122
	 * @param excludeFolders list of IPaths describing folders to ignore while searching
123
	 * @param dest destination to put the extracted source
124
	 * @param monitor progress monitor
125
	 * @throws CoreException if there is a problem extracting source from the zip
126
	 * @since 3.4
127
	 */
128
	protected void extractJavaSource(File file, List excludeFolders, IResource dest, IProgressMonitor monitor) throws CoreException {
129
		ZipFile zipFile = null;
130
		try {
131
			zipFile = new ZipFile(file);
132
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
133
			ArrayList collected = new ArrayList();
134
			collectJavaSourceFromRoot(provider, excludeFolders, collected);
135
			importContent(provider.getRoot(), dest.getFullPath(), provider, collected, monitor);
136
		} catch (IOException e) {
137
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
138
			throw new CoreException(status);
139
		} finally {
140
			if (zipFile != null) {
141
				try {
142
					zipFile.close();
143
				} catch (IOException e) {
144
				}
145
			}
146
		}
147
	}
148
149
	protected void extractJavaResources(File file, IResource dest, IProgressMonitor monitor) throws CoreException {
150
		ZipFile zipFile = null;
151
		try {
152
			zipFile = new ZipFile(file);
153
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
154
			ArrayList collected = new ArrayList();
155
			collectJavaResources(provider, provider.getRoot(), collected);
156
			importContent(provider.getRoot(), dest.getFullPath(), provider, collected, monitor);
157
		} catch (IOException e) {
158
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
159
			throw new CoreException(status);
160
		} finally {
161
			if (zipFile != null) {
162
				try {
163
					zipFile.close();
164
				} catch (IOException e) {
165
				}
166
			}
167
		}
168
	}
169
170
	protected void importArchive(IProject project, File archive, IPath destPath) throws CoreException {
171
		try {
172
			if (destPath.segmentCount() > 2)
173
				CoreUtility.createFolder(project.getFolder(destPath.removeLastSegments(1)));
174
			IFile file = project.getFile(destPath);
175
			FileInputStream fstream = new FileInputStream(archive);
176
			if (file.exists())
177
				file.setContents(fstream, true, false, null);
178
			else
179
				file.create(fstream, true, null);
180
			fstream.close();
181
		} catch (IOException e) {
182
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.OK, e.getMessage(), e);
183
			throw new CoreException(status);
184
		}
185
	}
186
187
	private void collectResources(ZipFileStructureProvider provider, Object element, boolean excludeMeta, ArrayList collected) {
188
		List children = provider.getChildren(element);
189
		if (children != null && !children.isEmpty()) {
190
			for (int i = 0; i < children.size(); i++) {
191
				Object curr = children.get(i);
192
				if (provider.isFolder(curr)) {
193
					if (!excludeMeta || !provider.getLabel(curr).equals("META-INF")) { //$NON-NLS-1$
194
						collectResources(provider, curr, excludeMeta, collected);
195
					}
196
				} else if (!provider.getLabel(curr).endsWith(".class")) { //$NON-NLS-1$
197
					collected.add(curr);
198
				}
199
			}
200
		}
201
	}
202
203
	/**
204
	 * Recursively searches through the zip files searching for files inside of
205
	 * the specified folder.  The files found will be added to the given list.
206
	 * @param provider zip provider
207
	 * @param element element of the zip currently being looked at
208
	 * @param folderPath location of the folder to get resources from
209
	 * @param collected list of files found
210
	 * @since 3.4
211
	 */
212
	protected void collectResourcesFromFolder(ZipFileStructureProvider provider, Object element, IPath folderPath, ArrayList collected) {
213
		List children = provider.getChildren(element);
214
		if (children != null && !children.isEmpty()) {
215
			for (int i = 0; i < children.size(); i++) {
216
				Object curr = children.get(i);
217
				if (provider.isFolder(curr)) {
218
					if (provider.getLabel(curr).equals(folderPath.segment(0))) {
219
						if (folderPath.segmentCount() > 1) {
220
							collectResourcesFromFolder(provider, curr, folderPath.removeFirstSegments(1), collected);
221
						} else {
222
							collectResources(provider, curr, false, collected);
223
						}
224
					}
225
				}
226
			}
227
		}
228
	}
229
230
	/**
231
	 * Searches through the zip file for java source folders.  Collects the files
232
	 * within the source folders.  If a folder is in the list of folder paths to
233
	 * ignore, the folder will be skipped.
234
	 * @param provider zip provider
235
	 * @param ignoreFolders list of IPaths describing folders to ignore
236
	 * @param collected list that source files will be added to
237
	 * @since 3.4
238
	 */
239
	protected void collectJavaSourceFromRoot(ZipFileStructureProvider provider, List ignoreFolders, ArrayList collected) {
240
		List children = provider.getChildren(provider.getRoot());
241
		if (children != null && !children.isEmpty()) {
242
			for (int i = 0; i < children.size(); i++) {
243
				Object curr = children.get(i);
244
				if (provider.isFolder(curr) && folderContainsFileExtension(provider, curr, ".java")) { //$NON-NLS-1$
245
					// Check if we are in an ignored folder
246
					List ignoreSubFolders = new ArrayList();
247
					boolean ignoreThisChild = false;
248
					for (Iterator iterator = ignoreFolders.iterator(); iterator.hasNext();) {
249
						IPath currentPath = (IPath) iterator.next();
250
						if (provider.getLabel(curr).equals(currentPath.segment(0))) {
251
							if (currentPath.segmentCount() > 1) {
252
								// There is a subfolder that should be ignored
253
								ignoreSubFolders.add(currentPath.removeFirstSegments(1));
254
							} else {
255
								// This folder should be ignored
256
								ignoreThisChild = true;
257
								break;
258
							}
259
						}
260
					}
261
					if (!ignoreThisChild) {
262
						collectJavaSource(provider, curr, ignoreSubFolders, collected);
263
					}
264
				}
265
			}
266
		}
267
	}
268
269
	/**
270
	 * Recursively searches the children of the given element inside of a zip file. 
271
	 * If the folder path is in the set of folders to ignore, the folder will be skipped.
272
	 * All files found, except for .class files, will be added. The given list will be
273
	 * updated with the source files.
274
	 * 
275
	 * @param provider zip provider
276
	 * @param element current element inside the zip
277
	 * @param ignoreFolders list of IPath folder paths to skip while searching
278
	 * @param collected list to update with new files found to import
279
	 * @since 3.4
280
	 */
281
	protected void collectJavaSource(ZipFileStructureProvider provider, Object element, List ignoreFolders, ArrayList collected) {
282
		List children = provider.getChildren(element);
283
		if (children != null && !children.isEmpty()) {
284
			for (int i = 0; i < children.size(); i++) {
285
				Object curr = children.get(i);
286
				if (provider.isFolder(curr)) {
287
					// Check if we are in an ignored folder
288
					List ignoreSubFolders = new ArrayList();
289
					boolean ignoreThisChild = false;
290
					for (Iterator iterator = ignoreFolders.iterator(); iterator.hasNext();) {
291
						IPath currentPath = (IPath) iterator.next();
292
						if (provider.getLabel(curr).equals(currentPath.segment(0))) {
293
							if (currentPath.segmentCount() > 1) {
294
								// There is a subfolder that should be ignored.  Remove segment referencing current folder.
295
								ignoreSubFolders.add(currentPath.removeFirstSegments(1));
296
							} else {
297
								// This folder should be ignored
298
								ignoreThisChild = true;
299
								break;
300
							}
301
						}
302
					}
303
					if (!ignoreThisChild) {
304
						collectJavaSource(provider, curr, ignoreSubFolders, collected);
305
					}
306
					// Add the file to the list
307
				} else if (!provider.getLabel(curr).endsWith(".class")) { //$NON-NLS-1$
308
					collected.add(curr);
309
				}
310
			}
311
		}
312
	}
313
314
	protected void collectNonJavaResources(ZipFileStructureProvider provider, Object element, ArrayList collected) {
315
		List children = provider.getChildren(element);
316
		if (children != null && !children.isEmpty()) {
317
			for (int i = 0; i < children.size(); i++) {
318
				Object curr = children.get(i);
319
				if (provider.isFolder(curr)) {
320
					if (!provider.getLabel(curr).equals("src") && !isClassFolder(provider, curr)) { //$NON-NLS-1$
321
						ArrayList list = new ArrayList();
322
						collectResources(provider, curr, false, list);
323
						collected.addAll(list);
324
					}
325
				} else if (!provider.getLabel(curr).endsWith(".class")) { //$NON-NLS-1$
326
					collected.add(curr);
327
				}
328
			}
329
		}
330
	}
331
332
	protected void collectAdditionalResources(ZipFileStructureProvider provider, Object element, ArrayList collected) {
333
		List children = provider.getChildren(element);
334
		if (children != null && !children.isEmpty()) {
335
			for (int i = 0; i < children.size(); i++) {
336
				Object curr = children.get(i);
337
				if (provider.isFolder(curr)) {
338
					// ignore source folders
339
					if (folderContainsFileExtension(provider, curr, ".java")) //$NON-NLS-1$
340
						continue;
341
					collected.add(curr);
342
				} else if (!provider.getLabel(curr).endsWith(".java")) { //$NON-NLS-1$
343
					collected.add(curr);
344
				}
345
			}
346
		}
347
	}
348
349
	protected void collectJavaFiles(ZipFileStructureProvider provider, Object element, ArrayList collected) {
350
		List children = provider.getChildren(element);
351
		if (children != null && !children.isEmpty()) {
352
			for (int i = 0; i < children.size(); i++) {
353
				Object curr = children.get(i);
354
				if (provider.isFolder(curr)) {
355
					if (provider.getLabel(curr).equals("src")) { //$NON-NLS-1$
356
						ArrayList list = new ArrayList();
357
						collectResources(provider, curr, false, list);
358
						collected.addAll(list);
359
					}
360
				}
361
			}
362
		}
363
	}
364
365
	protected void collectJavaResources(ZipFileStructureProvider provider, Object element, ArrayList collected) {
366
		List children = provider.getChildren(element);
367
		if (children != null && !children.isEmpty()) {
368
			for (int i = 0; i < children.size(); i++) {
369
				Object curr = children.get(i);
370
				if (provider.isFolder(curr)) {
371
					if (isClassFolder(provider, curr)) {
372
						ArrayList list = new ArrayList();
373
						collectResources(provider, curr, false, list);
374
						collected.addAll(list);
375
					}
376
				}
377
			}
378
		}
379
	}
380
381
	private boolean folderContainsFileExtension(ZipFileStructureProvider provider, Object element, String fileExtension) {
382
		List children = provider.getChildren(element);
383
		if (children != null && !children.isEmpty()) {
384
			for (int i = 0; i < children.size(); i++) {
385
				Object curr = children.get(i);
386
				if (provider.isFolder(curr)) {
387
					if (folderContainsFileExtension(provider, curr, fileExtension)) {
388
						return true;
389
					}
390
				} else if (provider.getLabel(curr).endsWith(fileExtension)) { //$NON-NLS-1$
391
					return true;
392
				}
393
			}
394
		}
395
		return false;
396
	}
397
398
	private boolean isClassFolder(ZipFileStructureProvider provider, Object element) {
399
		return folderContainsFileExtension(provider, element, ".class"); //$NON-NLS-1$
400
	}
401
402
	protected boolean hasEmbeddedSource(ZipFileStructureProvider provider) {
403
		List children = provider.getChildren(provider.getRoot());
404
		if (children != null && !children.isEmpty()) {
405
			for (int i = 0; i < children.size(); i++) {
406
				Object curr = children.get(i);
407
				if (provider.isFolder(curr) && provider.getLabel(curr).equals("src")) { //$NON-NLS-1$
408
					return true;
409
				}
410
			}
411
		}
412
		return false;
413
	}
414
415
	protected boolean containsCode(ZipFileStructureProvider provider) {
416
		List children = provider.getChildren(provider.getRoot());
417
		if (children != null && !children.isEmpty()) {
418
			for (int i = 0; i < children.size(); i++) {
419
				Object curr = children.get(i);
420
				if (provider.isFolder(curr) && isClassFolder(provider, curr)) {
421
					return true;
422
				}
423
			}
424
		}
425
		return false;
426
	}
427
428
	protected boolean containsCode(File file) {
429
		ZipFile zipFile = null;
430
		try {
431
			zipFile = new ZipFile(file);
432
			return containsCode(new ZipFileStructureProvider(zipFile));
433
		} catch (IOException e) {
434
		} finally {
435
			if (zipFile != null) {
436
				try {
437
					zipFile.close();
438
				} catch (IOException e) {
439
				}
440
			}
441
		}
442
		return true;
443
	}
444
445
	protected String[] getTopLevelResources(File file) {
446
		ArrayList result = new ArrayList();
447
		ZipFile zipFile = null;
448
		try {
449
			zipFile = new ZipFile(file);
450
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
451
			List children = provider.getChildren(provider.getRoot());
452
			if (children != null && !children.isEmpty()) {
453
				for (int i = 0; i < children.size(); i++) {
454
					Object curr = children.get(i);
455
					if (provider.isFolder(curr)) {
456
						if (!isClassFolder(provider, curr))
457
							result.add(provider.getLabel(curr) + "/"); //$NON-NLS-1$
458
						else {
459
							if (!result.contains(".")) //$NON-NLS-1$
460
								result.add("."); //$NON-NLS-1$
461
						}
462
					} else {
463
						result.add(provider.getLabel(curr));
464
					}
465
				}
466
			}
467
		} catch (IOException e) {
468
		} finally {
469
			if (zipFile != null) {
470
				try {
471
					zipFile.close();
472
				} catch (IOException e) {
473
				}
474
			}
475
		}
476
		return (String[]) result.toArray(new String[result.size()]);
477
	}
478
479
}
(-)src/org/eclipse/pde/internal/ui/pderesources.properties (-6 / +4 lines)
Lines 1073-1082 Link Here
1073
PluginSelectionDialog_title = Plug-in Selection
1073
PluginSelectionDialog_title = Plug-in Selection
1074
PluginStructureCreator_name=Plug-in Structure Compare
1074
PluginStructureCreator_name=Plug-in Structure Compare
1075
PluginSelectionDialog_message = &Select a Plug-in:
1075
PluginSelectionDialog_message = &Select a Plug-in:
1076
PluginImportInfoDialog_message=Could not fully delete existing plug-ins with the same name.\nImporting the following plug-ins failed:
1076
PluginImportOperation_could_not_delete_project=Import operation could not delete the following project: {0}
1077
PluginImportInfoDialog_title=Deleting Plug-ins Failed
1078
PluginImportOperation_linking=Linking content...
1077
PluginImportOperation_linking=Linking content...
1079
PluginImportOperation_executionEnvironment=Plug-in ''{0}'' requires an ''{1}'' execution environment that is not supported by any of the installed JREs. Import anyway?
1078
PluginImportOperation_executionEnvironment=Plug-in ''{0}'' requires an ''{1}'' execution environment that is not supported by any of the installed JREs. Import anyway?
1079
PluginImportOperation_Importing_plugin=Importing {0}
1080
PluginImportWizard_runningConfigDesc=An application is currently running. Some of the selected plug-ins may not be imported if they are locked by it. Do you want to continue?
1080
PluginImportWizard_runningConfigDesc=An application is currently running. Some of the selected plug-ins may not be imported if they are locked by it. Do you want to continue?
1081
PluginImportWizard_runningConfigsDesc=Multiple applications are currently running. Some of the selected plug-ins may not be imported if they are locked by them. Do you want to continue?
1081
PluginImportWizard_runningConfigsDesc=Multiple applications are currently running. Some of the selected plug-ins may not be imported if they are locked by them. Do you want to continue?
1082
PluginImportWizard_runningConfigsTitle=Running Applications
1082
PluginImportWizard_runningConfigsTitle=Running Applications
Lines 1141-1151 Link Here
1141
ImportWizard_DetailedPage_filterDesc=Show latest version of plug-ins only
1141
ImportWizard_DetailedPage_filterDesc=Show latest version of plug-ins only
1142
ImportWizard_DetailedPage_search = &ID (* = any string, ? = any character):
1142
ImportWizard_DetailedPage_search = &ID (* = any string, ? = any character):
1143
1143
1144
ImportWizard_operation_creating = Creating projects from plug-ins...
1144
ImportWizard_operation_creating = Creating projects from plug-ins
1145
ImportWizard_operation_multiProblem = Problems detected while importing plug-ins
1145
ImportWizard_operation_multiProblem = Problems detected while importing plug-ins
1146
ImportWizard_operation_creating2 = Creating ''{0}''...
1146
ImportWizard_operation_importingSource== Importing source...
1147
ImportWizard_operation_copyingSource = Copying source...
1148
1149
FeatureImportWizard_FirstPage_title = Import Features
1147
FeatureImportWizard_FirstPage_title = Import Features
1150
FeatureImportWizard_FirstPage_desc = Create projects from features in the file system.
1148
FeatureImportWizard_FirstPage_desc = Create projects from features in the file system.
1151
FeatureImportWizard_FirstPage_runtimeLocation = &Choose from features in the target platform
1149
FeatureImportWizard_FirstPage_runtimeLocation = &Choose from features in the target platform
(-)src/org/eclipse/pde/internal/ui/PDEUIMessages.java (-5 / +4 lines)
Lines 1594-1602 Link Here
1594
1594
1595
	public static String PluginSelectionDialog_title;
1595
	public static String PluginSelectionDialog_title;
1596
	public static String PluginSelectionDialog_message;
1596
	public static String PluginSelectionDialog_message;
1597
	public static String PluginImportInfoDialog_message;
1597
	public static String PluginImportOperation_could_not_delete_project;
1598
1599
	public static String PluginImportInfoDialog_title;
1600
1598
1601
	public static String PluginImportOperation_linking;
1599
	public static String PluginImportOperation_linking;
1602
	public static String PluginContentPage_appQuestion;
1600
	public static String PluginContentPage_appQuestion;
Lines 1660-1667 Link Here
1660
1658
1661
	public static String ImportWizard_operation_creating;
1659
	public static String ImportWizard_operation_creating;
1662
	public static String ImportWizard_operation_multiProblem;
1660
	public static String ImportWizard_operation_multiProblem;
1663
	public static String ImportWizard_operation_creating2;
1661
	public static String ImportWizard_operation_importingSource;
1664
	public static String ImportWizard_operation_copyingSource;
1665
1662
1666
	public static String FeatureImportWizard_FirstPage_title;
1663
	public static String FeatureImportWizard_FirstPage_title;
1667
	public static String FeatureImportWizard_FirstPage_desc;
1664
	public static String FeatureImportWizard_FirstPage_desc;
Lines 2556-2561 Link Here
2556
2553
2557
	public static String PluginImportOperation_executionEnvironment;
2554
	public static String PluginImportOperation_executionEnvironment;
2558
2555
2556
	public static String PluginImportOperation_Importing_plugin;
2557
2559
	public static String PluginImportWizard_runningConfigDesc;
2558
	public static String PluginImportWizard_runningConfigDesc;
2560
2559
2561
	public static String PluginImportWizard_runningConfigsDesc;
2560
	public static String PluginImportWizard_runningConfigsDesc;
(-)META-INF/MANIFEST.MF (-1 / +4 lines)
Lines 114-120 Link Here
114
 org.eclipse.equinox.p2.core;bundle-version="[1.0.0,2.0.0)",
114
 org.eclipse.equinox.p2.core;bundle-version="[1.0.0,2.0.0)",
115
 org.eclipse.equinox.p2.director;bundle-version="[1.0.100,2.0.0)",
115
 org.eclipse.equinox.p2.director;bundle-version="[1.0.100,2.0.0)",
116
 org.eclipse.equinox.p2.artifact.repository;bundle-version="[1.0.100,2.0.0)",
116
 org.eclipse.equinox.p2.artifact.repository;bundle-version="[1.0.100,2.0.0)",
117
 org.eclipse.equinox.p2.metadata.repository;bundle-version="[1.0.100,2.0.0)"
117
 org.eclipse.equinox.p2.metadata.repository;bundle-version="[1.0.100,2.0.0)",
118
 org.eclipse.equinox.p2.publisher;bundle-version="[1.0.0,2.0.0)",
119
 org.eclipse.equinox.frameworkadmin;bundle-version="1.0.100",
120
 org.eclipse.equinox.frameworkadmin.equinox;bundle-version="1.0.100"
118
Eclipse-LazyStart: true
121
Eclipse-LazyStart: true
119
Import-Package: com.ibm.icu.text,
122
Import-Package: com.ibm.icu.text,
120
 org.eclipse.jdt.debug.core
123
 org.eclipse.jdt.debug.core
(-)src/org/eclipse/pde/ui/launcher/AbstractPDELaunchConfiguration.java (-19 / +175 lines)
Lines 11-31 Link Here
11
package org.eclipse.pde.ui.launcher;
11
package org.eclipse.pde.ui.launcher;
12
12
13
import java.io.File;
13
import java.io.File;
14
import java.util.ArrayList;
14
import java.io.IOException;
15
import java.util.Map;
15
import java.util.*;
16
import org.eclipse.core.resources.IMarker;
16
import org.eclipse.core.resources.IMarker;
17
import org.eclipse.core.resources.IProject;
17
import org.eclipse.core.resources.IProject;
18
import org.eclipse.core.resources.IResource;
18
import org.eclipse.core.runtime.*;
19
import org.eclipse.core.runtime.*;
19
import org.eclipse.debug.core.*;
20
import org.eclipse.debug.core.*;
20
import org.eclipse.debug.core.model.LaunchConfigurationDelegate;
21
import org.eclipse.debug.core.model.LaunchConfigurationDelegate;
21
import org.eclipse.jdt.core.IJavaModelMarker;
22
import org.eclipse.jdt.core.IJavaModelMarker;
23
import org.eclipse.equinox.internal.frameworkadmin.equinox.EquinoxConstants;
24
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
25
import org.eclipse.equinox.internal.p2.director.DirectorActivator;
26
import org.eclipse.equinox.internal.provisional.frameworkadmin.*;
27
import org.eclipse.equinox.internal.provisional.p2.engine.IProfile;
28
import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry;
29
import org.eclipse.equinox.p2.publisher.PublisherInfo;
30
import org.eclipse.equinox.p2.publisher.PublisherResult;
31
import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction;
22
import org.eclipse.jdt.launching.*;
32
import org.eclipse.jdt.launching.*;
23
import org.eclipse.jface.dialogs.MessageDialog;
33
import org.eclipse.jface.dialogs.MessageDialog;
34
import org.eclipse.osgi.service.resolver.BundleDescription;
35
import org.eclipse.pde.core.plugin.IPluginModelBase;
24
import org.eclipse.pde.core.plugin.TargetPlatform;
36
import org.eclipse.pde.core.plugin.TargetPlatform;
25
import org.eclipse.pde.internal.core.TargetPlatformHelper;
37
import org.eclipse.pde.internal.core.TargetPlatformHelper;
26
import org.eclipse.pde.internal.core.builders.PDEMarkerFactory;
38
import org.eclipse.pde.internal.core.builders.PDEMarkerFactory;
27
import org.eclipse.pde.internal.ui.*;
39
import org.eclipse.pde.internal.ui.*;
28
import org.eclipse.pde.internal.ui.launcher.*;
40
import org.eclipse.pde.internal.ui.launcher.*;
41
import org.osgi.framework.*;
42
import org.osgi.util.tracker.ServiceTracker;
29
43
30
/**
44
/**
31
 * An abstract launch delegate for PDE-based launch configurations
45
 * An abstract launch delegate for PDE-based launch configurations
Lines 62-89 Link Here
62
				}
76
				}
63
				throw e;
77
				throw e;
64
			}
78
			}
79
65
			// if restarting, remove the restart flag from the launch config
80
			// if restarting, remove the restart flag from the launch config
66
			if (configuration.getAttribute(IPDEUIConstants.RESTART, false) && configuration instanceof ILaunchConfigurationWorkingCopy) {
81
			if (configuration.getAttribute(IPDEUIConstants.RESTART, false) && configuration instanceof ILaunchConfigurationWorkingCopy) {
67
				((ILaunchConfigurationWorkingCopy) configuration).setAttribute(IPDEUIConstants.RESTART, false);
82
				((ILaunchConfigurationWorkingCopy) configuration).setAttribute(IPDEUIConstants.RESTART, false);
68
				((ILaunchConfigurationWorkingCopy) configuration).doSave();
83
				((ILaunchConfigurationWorkingCopy) configuration).doSave();
69
			}
84
			}
70
			VMRunnerConfiguration runnerConfig = new VMRunnerConfiguration(getMainClass(), getClasspath(configuration));
85
71
			runnerConfig.setVMArguments(getVMArguments(configuration));
86
//			createP2Profile(configuration, monitor);
72
			runnerConfig.setProgramArguments(getProgramArguments(configuration));
87
73
			runnerConfig.setWorkingDirectory(getWorkingDirectory(configuration).getAbsolutePath());
88
//			VMRunnerConfiguration runnerConfig = new VMRunnerConfiguration(getMainClass(), getClasspath(configuration));
74
			runnerConfig.setEnvironment(getEnvironment(configuration));
89
//			runnerConfig.setVMArguments(getVMArguments(configuration));
75
			runnerConfig.setVMSpecificAttributesMap(getVMSpecificAttributesMap(configuration));
90
//			runnerConfig.setProgramArguments(getProgramArguments(configuration));
76
91
//			runnerConfig.setWorkingDirectory(getWorkingDirectory(configuration).getAbsolutePath());
77
			monitor.worked(1);
92
//			runnerConfig.setEnvironment(getEnvironment(configuration));
78
93
//			runnerConfig.setVMSpecificAttributesMap(getVMSpecificAttributesMap(configuration));
79
			setDefaultSourceLocator(configuration);
94
//
80
			manageLaunch(launch);
95
//			monitor.worked(1);
81
			IVMRunner runner = getVMRunner(configuration, mode);
96
//
82
			if (runner != null)
97
//			setDefaultSourceLocator(configuration);
83
				runner.run(runnerConfig, launch, monitor);
98
//			manageLaunch(launch);
84
			else
99
//			IVMRunner runner = getVMRunner(configuration, mode);
85
				monitor.setCanceled(true);
100
//			if (runner != null)
86
			monitor.done();
101
//				runner.run(runnerConfig, launch, monitor);
102
//			else
103
//				monitor.setCanceled(true);
104
//			monitor.done();
105
106
			setupFrameworkAdmin(configuration);
107
87
		} catch (final CoreException e) {
108
		} catch (final CoreException e) {
88
			monitor.setCanceled(true);
109
			monitor.setCanceled(true);
89
			LauncherUtils.getDisplay().syncExec(new Runnable() {
110
			LauncherUtils.getDisplay().syncExec(new Runnable() {
Lines 95-100 Link Here
95
	}
116
	}
96
117
97
	/**
118
	/**
119
	 * @since 3.5
120
	 */
121
	protected void createP2Profile(ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException {
122
		IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(DirectorActivator.context, IProfileRegistry.class.getName());
123
		if (profileRegistry == null)
124
			throw new CoreException(new Status(IStatus.ERROR, PDEPlugin.getPluginId(), "ProfileRegistry unavailable"));
125
		IProfile profile = profileRegistry.addProfile("Tempy");
126
127
		Set models = LaunchPluginValidator.parsePlugins(configuration, IPDELauncherConstants.SELECTED_WORKSPACE_PLUGINS);
128
		List bundleDescriptions = new ArrayList(models.size());
129
		for (Iterator iterator = models.iterator(); iterator.hasNext();) {
130
			IPluginModelBase currentModel = (IPluginModelBase) iterator.next();
131
			BundleDescription bd = currentModel.getBundleDescription();
132
133
			// TODO Unclear if we can use the existing bundle description, or we need to recreate
134
			IResource res = currentModel.getUnderlyingResource();
135
			bd = BundlesAction.createBundleDescription(new File(res.getLocationURI()));
136
137
			if (bd != null) {
138
				bundleDescriptions.add(bd);
139
			}
140
		}
141
142
		BundlesAction bundlesAction = new BundlesAction((BundleDescription[]) bundleDescriptions.toArray(new BundleDescription[bundleDescriptions.size()]));
143
		PublisherResult results = new PublisherResult();
144
		IStatus status = bundlesAction.perform(new PublisherInfo(), results, monitor);
145
146
		System.out.println(results.getIUs(null, null));
147
148
		models = LaunchPluginValidator.parsePlugins(configuration, IPDELauncherConstants.SELECTED_TARGET_PLUGINS);
149
		bundleDescriptions = new ArrayList(models.size());
150
		for (Iterator iterator = models.iterator(); iterator.hasNext();) {
151
			IPluginModelBase currentModel = (IPluginModelBase) iterator.next();
152
			BundleDescription bd = currentModel.getBundleDescription();
153
154
			// TODO Unclear if we can use the existing bundle description, or we need to recreate
155
			IResource res = currentModel.getUnderlyingResource();
156
			bd = BundlesAction.createBundleDescription(new File(res.getLocationURI()));
157
158
			if (bd != null) {
159
				bundleDescriptions.add(bd);
160
			}
161
		}
162
163
		bundlesAction = new BundlesAction((BundleDescription[]) bundleDescriptions.toArray(new BundleDescription[bundleDescriptions.size()]));
164
		results = new PublisherResult();
165
		status = bundlesAction.perform(new PublisherInfo(), results, monitor);
166
167
		System.out.println(results.getIUs(null, null));
168
169
	}
170
171
	/**
172
	 * @since 3.5
173
	 */
174
	protected void setupFrameworkAdmin(ILaunchConfiguration configuration) throws CoreException {
175
		ServiceReference serviceRef = PDEPlugin.getDefault().getBundleContext().getServiceReference(FrameworkAdmin.class.getName());
176
		PDEPlugin.getDefault().getBundleContext().getService(serviceRef);
177
178
		final String FILTER_OBJECTCLASS = "(" + Constants.OBJECTCLASS + "=" + FrameworkAdmin.class.getName() + ")";
179
		final String filterFwName = "(" + FrameworkAdmin.SERVICE_PROP_KEY_FW_NAME + "=Equinox)";
180
		final String filterLauncherName = "(" + FrameworkAdmin.SERVICE_PROP_KEY_LAUNCHER_NAME + "=Eclipse.exe)";
181
		final String filterFwAdmin = "(&" + FILTER_OBJECTCLASS + filterFwName + filterLauncherName + ")";
182
183
		Filter filter;
184
		ServiceTracker fwAdminTracker = null;
185
		try {
186
			filter = PDEPlugin.getDefault().getBundleContext().createFilter(filterFwAdmin);
187
			fwAdminTracker = new ServiceTracker(PDEPlugin.getDefault().getBundleContext(), filter, null);
188
			fwAdminTracker.open();
189
		} catch (InvalidSyntaxException e) {
190
			// never happens
191
			e.printStackTrace();
192
		}
193
194
		if (fwAdminTracker != null) {
195
			FrameworkAdmin fwAdmin = (FrameworkAdmin) fwAdminTracker.getService();
196
197
			Manipulator tempManipulator = fwAdmin.getRunningManipulator();
198
199
			Manipulator manipulator = fwAdmin.getManipulator();
200
201
			LauncherData launcherData = new LauncherData(EquinoxConstants.FW_NAME, EquinoxConstants.FW_VERSION, EquinoxConstants.LAUNCHER_NAME, EquinoxConstants.LAUNCHER_VERSION);
202
			launcherData.setLauncher(new File(Platform.getInstallLocation().getURL().getFile(), "eclipse.exe"));
203
			launcherData.setLauncherConfigLocation(new File(getConfigDir(configuration), "eclipse.ini"));
204
205
			launcherData.setJvmArgs(getVMArguments(configuration));
206
			// TODO Simplify how we get the VM without breaking API, #getVMRunner() will no longer be used
207
			launcherData.setJvm(VMHelper.createLauncher(configuration).getInstallLocation());
208
			launcherData.setProgramArgs(getProgramArguments(configuration));
209
210
			launcherData.setFwConfigLocation(getConfigDir(configuration));
211
212
			// TODO What else needs to be set
213
			//		data.setFwJar(fwJar);
214
			//		data.setFwPersistentDataLocation(fwPersistentDataLocation, clean);
215
//			data.setHome(home);
216
217
			// TODO Need to account for the following methods
218
			//		VMRunnerConfiguration runnerConfig = new VMRunnerConfiguration(getMainClass(), getClasspath(configuration));
219
			//		runnerConfig.setEnvironment(getEnvironment(configuration));
220
			//		runnerConfig.setVMSpecificAttributesMap(getVMSpecificAttributesMap(configuration));
221
222
			ConfigData configData = new ConfigData(EquinoxConstants.FW_NAME, EquinoxConstants.FW_VERSION, EquinoxConstants.LAUNCHER_NAME, EquinoxConstants.LAUNCHER_VERSION);
223
224
			IPluginModelBase[] plugins = LaunchPluginValidator.getPluginList(configuration);
225
			List launchingBundles = new ArrayList(plugins.length);
226
			for (int i = 0; i < plugins.length; i++) {
227
				launchingBundles.add(new BundleInfo(plugins[i].getInstallLocation()));
228
			}
229
			configData.setBundles((BundleInfo[]) launchingBundles.toArray(new BundleInfo[launchingBundles.size()]));
230
231
			// TODO What else needs to be set
232
			//		configData.setBeginningFwStartLevel(startLevel);
233
			//		configData.setFwDependentProps(props);
234
			//		configData.setFwIndependentProps(props);
235
			//		configData.setInitialBundleStartLevel(startLevel);
236
237
			manipulator.setLauncherData(launcherData);
238
			manipulator.setConfigData(configData);
239
240
			try {
241
242
				manipulator.save(false);
243
244
				fwAdmin.launch(manipulator, getWorkingDirectory(configuration));
245
246
			} catch (IOException e) {
247
				// TODO Translate?
248
				throw new CoreException(new Status(IStatus.ERROR, PDEPlugin.getPluginId(), "Error trying to launch framework", e));
249
			}
250
		}
251
	}
252
253
	/**
98
	 * Returns the VM runner for the given launch mode to use when launching the
254
	 * Returns the VM runner for the given launch mode to use when launching the
99
	 * given configuration.
255
	 * given configuration.
100
	 *  
256
	 *  
(-)src/org/eclipse/pde/internal/ui/wizards/imports/PluginImportHelper.java (+389 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.pde.internal.ui.wizards.imports;
12
13
import java.io.*;
14
import java.lang.reflect.InvocationTargetException;
15
import java.util.*;
16
import java.util.zip.ZipFile;
17
import org.eclipse.core.resources.IFile;
18
import org.eclipse.core.runtime.*;
19
import org.eclipse.pde.internal.ui.PDEPlugin;
20
import org.eclipse.ui.dialogs.IOverwriteQuery;
21
import org.eclipse.ui.wizards.datatransfer.*;
22
23
/**
24
 * Helper class for the plugin import operation.  Contains methods to assist in the copying and extracting
25
 * of jar a folder files.
26
 */
27
public class PluginImportHelper {
28
29
	/**
30
	 * Imports the contents of a zip file or folder, extracting the necessary files and
31
	 * putting them in the specified destination.  
32
	 * @param source the file or folder to import from, should either be the root of the zip file or the File representing the folder
33
	 * @param dstPath
34
	 * @param provider
35
	 * @param filesToImport
36
	 * @param monitor
37
	 * @throws CoreException
38
	 */
39
	public static void importContent(Object source, IPath dstPath, IImportStructureProvider provider, List filesToImport, IProgressMonitor monitor) throws CoreException {
40
		IOverwriteQuery query = new IOverwriteQuery() {
41
			public String queryOverwrite(String file) {
42
				return ALL;
43
			}
44
		};
45
		try {
46
			ImportOperation op = new ImportOperation(dstPath, source, provider, query);
47
			op.setCreateContainerStructure(false);
48
			if (filesToImport != null) {
49
				op.setFilesToImport(filesToImport);
50
			}
51
			op.run(monitor);
52
		} catch (InvocationTargetException e) {
53
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
54
			throw new CoreException(status);
55
		} catch (InterruptedException e) {
56
			throw new OperationCanceledException(e.getMessage());
57
		}
58
	}
59
60
	/**
61
	 * Extracts the contents of the specified zip file to the specified destination
62
	 * @param file
63
	 * @param dstPath
64
	 * @param monitor
65
	 * @throws CoreException
66
	 */
67
	public static void extractArchive(File file, IPath dstPath, IProgressMonitor monitor) throws CoreException {
68
		ZipFile zipFile = null;
69
		try {
70
			zipFile = new ZipFile(file);
71
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
72
			importContent(provider.getRoot(), dstPath, provider, null, monitor);
73
		} catch (IOException e) {
74
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
75
			throw new CoreException(status);
76
		} finally {
77
			if (zipFile != null) {
78
				try {
79
					zipFile.close();
80
				} catch (IOException e) {
81
				}
82
			}
83
		}
84
	}
85
86
	/**
87
	 * Extracts all of the files and subfolders from a single folder within an archive file.
88
	 * @param file archive file to search for files
89
	 * @param folderPath path to the folder to extract from
90
	 * @param dstPath destination to import content to
91
	 * @param monitor progress monitor
92
	 * @throws CoreException if a problem occurs while extracting
93
	 * @since 3.4
94
	 */
95
	public static void extractFolderFromArchive(File file, IPath folderPath, IPath dstPath, IProgressMonitor monitor) throws CoreException {
96
		ZipFile zipFile = null;
97
		try {
98
			zipFile = new ZipFile(file);
99
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
100
			ArrayList collected = new ArrayList();
101
			collectResourcesFromFolder(provider, provider.getRoot(), folderPath, collected);
102
			importContent(provider.getRoot(), dstPath, provider, collected, monitor);
103
		} catch (IOException e) {
104
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
105
			throw new CoreException(status);
106
		} finally {
107
			if (zipFile != null) {
108
				try {
109
					zipFile.close();
110
				} catch (IOException e) {
111
				}
112
			}
113
		}
114
	}
115
116
	/**
117
	 * Searches the given archive file for java source folders.  Imports the files in the
118
	 * source folders to the specified destination unless the folder is in the list of 
119
	 * folders to exclude. 
120
	 * @param file archive file to search for source in
121
	 * @param excludeFolders list of IPaths describing folders to ignore while searching
122
	 * @param dstPath full path to destination to put the extracted source
123
	 * @param monitor progress monitor
124
	 * @throws CoreException if there is a problem extracting source from the zip
125
	 */
126
	public static void extractJavaSourceFromArchive(File file, List excludeFolders, IPath dstPath, IProgressMonitor monitor) throws CoreException {
127
		ZipFile zipFile = null;
128
		try {
129
			zipFile = new ZipFile(file);
130
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
131
			ArrayList collected = new ArrayList();
132
			collectJavaSourceFromRoot(provider, excludeFolders, collected);
133
			importContent(provider.getRoot(), dstPath, provider, collected, monitor);
134
		} catch (IOException e) {
135
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e);
136
			throw new CoreException(status);
137
		} finally {
138
			if (zipFile != null) {
139
				try {
140
					zipFile.close();
141
				} catch (IOException e) {
142
				}
143
			}
144
		}
145
	}
146
147
	/**
148
	 * Copies an archive file to an IFile
149
	 * @param file
150
	 * @param dstFile
151
	 * @throws CoreException
152
	 */
153
	public static void copyArchive(File file, IFile dstFile, IProgressMonitor monitor) throws CoreException {
154
		try {
155
			FileInputStream fstream = new FileInputStream(file);
156
			if (dstFile.exists())
157
				dstFile.setContents(fstream, true, false, monitor);
158
			else
159
				dstFile.create(fstream, true, monitor);
160
			fstream.close();
161
		} catch (IOException e) {
162
			IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(), IStatus.OK, e.getMessage(), e);
163
			throw new CoreException(status);
164
		}
165
	}
166
167
	public static String[] getTopLevelResources(File file) {
168
		ArrayList result = new ArrayList();
169
		ZipFile zipFile = null;
170
		try {
171
			zipFile = new ZipFile(file);
172
			ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
173
			List children = provider.getChildren(provider.getRoot());
174
			if (children != null && !children.isEmpty()) {
175
				for (int i = 0; i < children.size(); i++) {
176
					Object curr = children.get(i);
177
					if (provider.isFolder(curr)) {
178
						if (!isClassFolder(provider, curr))
179
							result.add(provider.getLabel(curr) + "/"); //$NON-NLS-1$
180
						else {
181
							if (!result.contains(".")) //$NON-NLS-1$
182
								result.add("."); //$NON-NLS-1$
183
						}
184
					} else {
185
						result.add(provider.getLabel(curr));
186
					}
187
				}
188
			}
189
		} catch (IOException e) {
190
		} finally {
191
			if (zipFile != null) {
192
				try {
193
					zipFile.close();
194
				} catch (IOException e) {
195
				}
196
			}
197
		}
198
		return (String[]) result.toArray(new String[result.size()]);
199
	}
200
201
	public static void collectRequiredBundleFiles(IImportStructureProvider provider, Object element, ArrayList collected) {
202
		List children = provider.getChildren(element);
203
		if (children != null && !children.isEmpty()) {
204
			for (int i = 0; i < children.size(); i++) {
205
				Object curr = children.get(i);
206
				String name = provider.getLabel(curr);
207
				if (provider.isFolder(curr)) {
208
					if (!name.equals("src") && !isClassFolder(provider, curr)) { //$NON-NLS-1$
209
						ArrayList list = new ArrayList();
210
						collectResources(provider, curr, false, list);
211
						collected.addAll(list);
212
					}
213
				} else if (!name.endsWith(".class")) { //$NON-NLS-1$
214
					// Ignore the bundle signing files
215
					if (!(provider.getFullPath(curr).indexOf("META-INF/") != -1 && (name.endsWith(".RSA") || name.endsWith(".DSA") || name.endsWith(".SF")))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
216
						collected.add(curr);
217
					}
218
				}
219
220
			}
221
		}
222
	}
223
224
	public static void collectNonJavaFiles(IImportStructureProvider provider, Object element, ArrayList collected) {
225
		List children = provider.getChildren(element);
226
		if (children != null && !children.isEmpty()) {
227
			for (int i = 0; i < children.size(); i++) {
228
				Object curr = children.get(i);
229
				if (provider.isFolder(curr)) {
230
					// ignore source folders
231
					if (folderContainsFileExtension(provider, curr, ".java")) //$NON-NLS-1$
232
						continue;
233
					collected.add(curr);
234
				} else if (!provider.getLabel(curr).endsWith(".java")) { //$NON-NLS-1$
235
					collected.add(curr);
236
				}
237
			}
238
		}
239
	}
240
241
	private static void collectResources(IImportStructureProvider provider, Object element, boolean excludeMeta, ArrayList collected) {
242
		List children = provider.getChildren(element);
243
		if (children != null && !children.isEmpty()) {
244
			for (int i = 0; i < children.size(); i++) {
245
				Object curr = children.get(i);
246
				if (provider.isFolder(curr)) {
247
					if (!excludeMeta || !provider.getLabel(curr).equals("META-INF")) { //$NON-NLS-1$
248
						collectResources(provider, curr, excludeMeta, collected);
249
					}
250
				} else if (!provider.getLabel(curr).endsWith(".class")) { //$NON-NLS-1$
251
					collected.add(curr);
252
				}
253
			}
254
		}
255
	}
256
257
	/**
258
	 * Recursively searches through the zip files searching for files inside of
259
	 * the specified folder.  The files found will be added to the given list.
260
	 * @param provider zip provider
261
	 * @param element element of the zip currently being looked at
262
	 * @param folderPath location of the folder to get resources from
263
	 * @param collected list of files found
264
	 * @since 3.4
265
	 */
266
	private static void collectResourcesFromFolder(ZipFileStructureProvider provider, Object element, IPath folderPath, ArrayList collected) {
267
		List children = provider.getChildren(element);
268
		if (children != null && !children.isEmpty()) {
269
			for (int i = 0; i < children.size(); i++) {
270
				Object curr = children.get(i);
271
				if (provider.isFolder(curr)) {
272
					if (provider.getLabel(curr).equals(folderPath.segment(0))) {
273
						if (folderPath.segmentCount() > 1) {
274
							collectResourcesFromFolder(provider, curr, folderPath.removeFirstSegments(1), collected);
275
						} else {
276
							collectResources(provider, curr, false, collected);
277
						}
278
					}
279
				}
280
			}
281
		}
282
	}
283
284
	/**
285
	 * Searches through the zip file for java source folders.  Collects the files
286
	 * within the source folders.  If a folder is in the list of folder paths to
287
	 * ignore, the folder will be skipped.
288
	 * @param provider zip provider
289
	 * @param ignoreFolders list of IPaths describing folders to ignore
290
	 * @param collected list that source files will be added to
291
	 * @since 3.4
292
	 */
293
	private static void collectJavaSourceFromRoot(ZipFileStructureProvider provider, List ignoreFolders, ArrayList collected) {
294
		List children = provider.getChildren(provider.getRoot());
295
		if (children != null && !children.isEmpty()) {
296
			for (int i = 0; i < children.size(); i++) {
297
				Object curr = children.get(i);
298
				if (provider.isFolder(curr) && folderContainsFileExtension(provider, curr, ".java")) { //$NON-NLS-1$
299
					// Check if we are in an ignored folder
300
					List ignoreSubFolders = new ArrayList();
301
					boolean ignoreThisChild = false;
302
					for (Iterator iterator = ignoreFolders.iterator(); iterator.hasNext();) {
303
						IPath currentPath = (IPath) iterator.next();
304
						if (provider.getLabel(curr).equals(currentPath.segment(0))) {
305
							if (currentPath.segmentCount() > 1) {
306
								// There is a subfolder that should be ignored
307
								ignoreSubFolders.add(currentPath.removeFirstSegments(1));
308
							} else {
309
								// This folder should be ignored
310
								ignoreThisChild = true;
311
								break;
312
							}
313
						}
314
					}
315
					if (!ignoreThisChild) {
316
						collectJavaSource(provider, curr, ignoreSubFolders, collected);
317
					}
318
				}
319
			}
320
		}
321
	}
322
323
	/**
324
	 * Recursively searches the children of the given element inside of a zip file. 
325
	 * If the folder path is in the set of folders to ignore, the folder will be skipped.
326
	 * All files found, except for .class files, will be added. The given list will be
327
	 * updated with the source files.
328
	 * 
329
	 * @param provider zip provider
330
	 * @param element current element inside the zip
331
	 * @param ignoreFolders list of IPath folder paths to skip while searching
332
	 * @param collected list to update with new files found to import
333
	 * @since 3.4
334
	 */
335
	private static void collectJavaSource(ZipFileStructureProvider provider, Object element, List ignoreFolders, ArrayList collected) {
336
		List children = provider.getChildren(element);
337
		if (children != null && !children.isEmpty()) {
338
			for (int i = 0; i < children.size(); i++) {
339
				Object curr = children.get(i);
340
				if (provider.isFolder(curr)) {
341
					// Check if we are in an ignored folder
342
					List ignoreSubFolders = new ArrayList();
343
					boolean ignoreThisChild = false;
344
					for (Iterator iterator = ignoreFolders.iterator(); iterator.hasNext();) {
345
						IPath currentPath = (IPath) iterator.next();
346
						if (provider.getLabel(curr).equals(currentPath.segment(0))) {
347
							if (currentPath.segmentCount() > 1) {
348
								// There is a subfolder that should be ignored.  Remove segment referencing current folder.
349
								ignoreSubFolders.add(currentPath.removeFirstSegments(1));
350
							} else {
351
								// This folder should be ignored
352
								ignoreThisChild = true;
353
								break;
354
							}
355
						}
356
					}
357
					if (!ignoreThisChild) {
358
						collectJavaSource(provider, curr, ignoreSubFolders, collected);
359
					}
360
					// Add the file to the list
361
				} else if (!provider.getLabel(curr).endsWith(".class")) { //$NON-NLS-1$
362
					collected.add(curr);
363
				}
364
			}
365
		}
366
	}
367
368
	private static boolean folderContainsFileExtension(IImportStructureProvider provider, Object element, String fileExtension) {
369
		List children = provider.getChildren(element);
370
		if (children != null && !children.isEmpty()) {
371
			for (int i = 0; i < children.size(); i++) {
372
				Object curr = children.get(i);
373
				if (provider.isFolder(curr)) {
374
					if (folderContainsFileExtension(provider, curr, fileExtension)) {
375
						return true;
376
					}
377
				} else if (provider.getLabel(curr).endsWith(fileExtension)) {
378
					return true;
379
				}
380
			}
381
		}
382
		return false;
383
	}
384
385
	private static boolean isClassFolder(IImportStructureProvider provider, Object element) {
386
		return folderContainsFileExtension(provider, element, ".class"); //$NON-NLS-1$
387
	}
388
389
}
(-)src/org/eclipse/pde/ui/tests/imports/BaseImportTestCase.java (-11 / +15 lines)
Lines 11-22 Link Here
11
package org.eclipse.pde.ui.tests.imports;
11
package org.eclipse.pde.ui.tests.imports;
12
12
13
import org.eclipse.core.resources.*;
13
import org.eclipse.core.resources.*;
14
import org.eclipse.core.runtime.*;
14
import org.eclipse.core.runtime.CoreException;
15
import org.eclipse.core.runtime.IStatus;
15
import org.eclipse.jdt.core.*;
16
import org.eclipse.jdt.core.*;
16
import org.eclipse.pde.core.plugin.IPluginModelBase;
17
import org.eclipse.pde.core.plugin.IPluginModelBase;
17
import org.eclipse.pde.core.plugin.PluginRegistry;
18
import org.eclipse.pde.core.plugin.PluginRegistry;
18
import org.eclipse.pde.internal.core.PDECore;
19
import org.eclipse.pde.internal.core.PDECore;
19
import org.eclipse.pde.internal.ui.PDEPlugin;
20
import org.eclipse.pde.internal.ui.wizards.imports.PluginImportOperation;
20
import org.eclipse.pde.internal.ui.wizards.imports.PluginImportOperation;
21
import org.eclipse.pde.internal.ui.wizards.imports.PluginImportWizard.ImportQuery;
21
import org.eclipse.pde.internal.ui.wizards.imports.PluginImportWizard.ImportQuery;
22
import org.eclipse.pde.ui.tests.PDETestCase;
22
import org.eclipse.pde.ui.tests.PDETestCase;
Lines 69-83 Link Here
69
	
69
	
70
	protected void runOperation(IPluginModelBase[] models, int type) {
70
	protected void runOperation(IPluginModelBase[] models, int type) {
71
		PluginImportOperation.IImportQuery query = new ImportQuery(getShell());
71
		PluginImportOperation.IImportQuery query = new ImportQuery(getShell());
72
		PluginImportOperation.IImportQuery executionQuery = new ImportQuery(getShell());
72
		PluginImportOperation.IImportQuery executionQuery = new ImportQuery(getShell());		
73
		final PluginImportOperation op = new PluginImportOperation(models, type, query, executionQuery, false);
73
		PluginImportOperation job = new PluginImportOperation(models, type, query, executionQuery, false);
74
74
		job.setRule(ResourcesPlugin.getWorkspace().getRoot());
75
		try {
75
		job.setSystem(true);
76
			PDEPlugin.getWorkspace().run(op, new NullProgressMonitor());
76
		job.schedule();
77
		} catch (OperationCanceledException e) {
77
		try{
78
			fail("Import Operation failed: " + e);
78
			job.join();
79
		} catch (CoreException e) {
79
		} catch (InterruptedException e){
80
			fail("Import Operation failed: " + e);
80
			fail("Job interupted: " + e.getMessage());
81
		}
82
		IStatus status = job.getResult();
83
		if (!status.isOK()){
84
			fail("Import Operation failed: " + status.toString());
81
		}
85
		}
82
	}
86
	}
83
87
(-)src/org/eclipse/pde/internal/core/ClasspathComputer.java (-24 / +22 lines)
Lines 35-45 Link Here
35
	private static final int SEVERITY_IGNORE = 1;
35
	private static final int SEVERITY_IGNORE = 1;
36
36
37
	public static void setClasspath(IProject project, IPluginModelBase model) throws CoreException {
37
	public static void setClasspath(IProject project, IPluginModelBase model) throws CoreException {
38
		IClasspathEntry[] entries = getClasspath(project, model, false, true);
38
		IClasspathEntry[] entries = getClasspath(project, model, null, false, true);
39
		JavaCore.create(project).setRawClasspath(entries, null);
39
		JavaCore.create(project).setRawClasspath(entries, null);
40
	}
40
	}
41
41
42
	public static IClasspathEntry[] getClasspath(IProject project, IPluginModelBase model, boolean clear, boolean overrideCompliance) throws CoreException {
42
	// TODO Javadoc
43
	public static IClasspathEntry[] getClasspath(IProject project, IPluginModelBase model, Map sourceLibraryMap, boolean clear, boolean overrideCompliance) throws CoreException {
43
		IJavaProject javaProject = JavaCore.create(project);
44
		IJavaProject javaProject = JavaCore.create(project);
44
		ArrayList result = new ArrayList();
45
		ArrayList result = new ArrayList();
45
		IBuild build = getBuild(project);
46
		IBuild build = getBuild(project);
Lines 53-59 Link Here
53
		result.add(createEntryUsingPreviousEntry(javaProject, ee, PDECore.REQUIRED_PLUGINS_CONTAINER_PATH));
54
		result.add(createEntryUsingPreviousEntry(javaProject, ee, PDECore.REQUIRED_PLUGINS_CONTAINER_PATH));
54
55
55
		// add own libraries/source
56
		// add own libraries/source
56
		addSourceAndLibraries(project, model, build, clear, result);
57
		addSourceAndLibraries(project, model, build, clear, sourceLibraryMap, result);
57
58
58
		IClasspathEntry[] entries = (IClasspathEntry[]) result.toArray(new IClasspathEntry[result.size()]);
59
		IClasspathEntry[] entries = (IClasspathEntry[]) result.toArray(new IClasspathEntry[result.size()]);
59
		IJavaModelStatus validation = JavaConventions.validateClasspath(javaProject, entries, javaProject.getOutputLocation());
60
		IJavaModelStatus validation = JavaConventions.validateClasspath(javaProject, entries, javaProject.getOutputLocation());
Lines 64-70 Link Here
64
		return (IClasspathEntry[]) result.toArray(new IClasspathEntry[result.size()]);
65
		return (IClasspathEntry[]) result.toArray(new IClasspathEntry[result.size()]);
65
	}
66
	}
66
67
67
	public static void addSourceAndLibraries(IProject project, IPluginModelBase model, IBuild build, boolean clear, ArrayList result) throws CoreException {
68
	private static void addSourceAndLibraries(IProject project, IPluginModelBase model, IBuild build, boolean clear, Map sourceLibraryMap, ArrayList result) throws CoreException {
68
69
69
		HashSet paths = new HashSet();
70
		HashSet paths = new HashSet();
70
71
Lines 87-96 Link Here
87
			if (buildEntry != null) {
88
			if (buildEntry != null) {
88
				addSourceFolder(buildEntry, project, paths, result);
89
				addSourceFolder(buildEntry, project, paths, result);
89
			} else {
90
			} else {
91
				IPath sourceAttachment = sourceLibraryMap != null ? (IPath) sourceLibraryMap.get(libraries[i].getName()) : null;
90
				if (libraries[i].getName().equals(".")) //$NON-NLS-1$
92
				if (libraries[i].getName().equals(".")) //$NON-NLS-1$
91
					addJARdPlugin(project, ClasspathUtilCore.getFilename(model), attrs, result);
93
					addJARdPlugin(project, ClasspathUtilCore.getFilename(model), sourceAttachment, attrs, result);
92
				else
94
				else
93
					addLibraryEntry(project, libraries[i], attrs, result);
95
					addLibraryEntry(project, libraries[i], sourceAttachment, attrs, result);
94
			}
96
			}
95
		}
97
		}
96
		if (libraries.length == 0) {
98
		if (libraries.length == 0) {
Lines 100-106 Link Here
100
					addSourceFolder(buildEntry, project, paths, result);
102
					addSourceFolder(buildEntry, project, paths, result);
101
				}
103
				}
102
			} else if (ClasspathUtilCore.hasBundleStructure(model)) {
104
			} else if (ClasspathUtilCore.hasBundleStructure(model)) {
103
				addJARdPlugin(project, ClasspathUtilCore.getFilename(model), attrs, result);
105
				IPath sourceAttachment = sourceLibraryMap != null ? (IPath) sourceLibraryMap.get(".") : null; //$NON-NLS-1$
106
				addJARdPlugin(project, ClasspathUtilCore.getFilename(model), sourceAttachment, attrs, result);
104
			}
107
			}
105
		}
108
		}
106
	}
109
	}
Lines 147-153 Link Here
147
		return (buildModel != null) ? buildModel.getBuild() : null;
150
		return (buildModel != null) ? buildModel.getBuild() : null;
148
	}
151
	}
149
152
150
	private static void addLibraryEntry(IProject project, IPluginLibrary library, IClasspathAttribute[] attrs, ArrayList result) throws JavaModelException {
153
	private static void addLibraryEntry(IProject project, IPluginLibrary library, IPath sourceAttachment, IClasspathAttribute[] attrs, ArrayList result) throws JavaModelException {
151
		String name = ClasspathUtilCore.expandLibraryName(library.getName());
154
		String name = ClasspathUtilCore.expandLibraryName(library.getName());
152
		IResource jarFile = project.findMember(name);
155
		IResource jarFile = project.findMember(name);
153
		if (jarFile == null)
156
		if (jarFile == null)
Lines 162-195 Link Here
162
			}
165
			}
163
		}
166
		}
164
167
165
		IClasspathEntry entry = createClasspathEntry(project, jarFile, name, attrs, library.isExported());
168
		IClasspathEntry entry = createClasspathEntry(project, jarFile, name, sourceAttachment, attrs, library.isExported());
166
		if (!result.contains(entry))
169
		if (!result.contains(entry))
167
			result.add(entry);
170
			result.add(entry);
168
	}
171
	}
169
172
170
	private static void addJARdPlugin(IProject project, String filename, IClasspathAttribute[] attrs, ArrayList result) {
173
	private static void addJARdPlugin(IProject project, String filename, IPath sourceAttachment, IClasspathAttribute[] attrs, ArrayList result) {
171
		String name = ClasspathUtilCore.expandLibraryName(filename);
174
		String name = ClasspathUtilCore.expandLibraryName(filename);
172
		IResource jarFile = project.findMember(name);
175
		IResource jarFile = project.findMember(name);
173
		if (jarFile != null) {
176
		if (jarFile != null) {
174
			IClasspathEntry entry = createClasspathEntry(project, jarFile, filename, attrs, true);
177
			IClasspathEntry entry = createClasspathEntry(project, jarFile, filename, sourceAttachment, attrs, true);
175
			if (!result.contains(entry))
178
			if (!result.contains(entry))
176
				result.add(entry);
179
				result.add(entry);
177
		}
180
		}
178
	}
181
	}
179
182
180
	private static IClasspathEntry createClasspathEntry(IProject project, IResource library, String fileName, IClasspathAttribute[] attrs, boolean isExported) {
183
	private static IClasspathEntry createClasspathEntry(IProject project, IResource library, String fileName, IPath sourceAttachment, IClasspathAttribute[] attrs, boolean isExported) {
181
		String sourceZipName = ClasspathUtilCore.getSourceZipName(fileName);
184
		IResource resource = sourceAttachment != null ? project.findMember(sourceAttachment) : project.findMember(ClasspathUtilCore.getSourceZipName(fileName));
182
		IResource resource = project.findMember(sourceZipName);
185
		// TODO This case may no longer be needed as the source can be any name, the source attachment should be specified in this case
183
		// if zip file does not exist, see if a directory with the source does.  This in necessary how we import source for individual source bundles.
186
//		if (resource == null) {
184
		if (resource == null && sourceZipName.endsWith(".zip")) { //$NON-NLS-1$
187
//			// If a specific library zip can't be found, look for the common source jar as is may have multiple source roots
185
			resource = project.findMember(sourceZipName.substring(0, sourceZipName.length() - 4));
188
//			resource = project.getFile(project.getName() + "src.zip"); //$NON-NLS-1$
186
			if (resource == null)
189
//		}		
187
				// if we can't find the the source for a library, then try to find the common source location set up to share source from one jar to all libraries.
190
		return JavaCore.newLibraryEntry(library.getFullPath(), resource == null ? null : resource.getFullPath(), null, new IAccessRule[0], attrs, isExported);
188
				// see PluginImportOperation.linkSourceArchives
189
				resource = project.getFile(project.getName() + "src.zip"); //$NON-NLS-1$
190
		}
191
		IPath srcAttachment = resource != null ? resource.getFullPath() : library.getFullPath();
192
		return JavaCore.newLibraryEntry(library.getFullPath(), srcAttachment, null, new IAccessRule[0], attrs, isExported);
193
	}
191
	}
194
192
195
	private static String getExecutionEnvironment(BundleDescription bundleDescription) {
193
	private static String getExecutionEnvironment(BundleDescription bundleDescription) {

Return to bug 245565