KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > wizards > imports > PluginImportOperation


1 /*******************************************************************************
2  * Copyright (c) 2000, 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.File JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Enumeration JavaDoc;
17 import java.util.HashMap JavaDoc;
18 import java.util.Hashtable JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.ListIterator JavaDoc;
21 import java.util.Stack JavaDoc;
22 import java.util.jar.JarFile JavaDoc;
23 import java.util.zip.ZipEntry JavaDoc;
24 import java.util.zip.ZipFile JavaDoc;
25
26 import org.eclipse.core.resources.IContainer;
27 import org.eclipse.core.resources.IFile;
28 import org.eclipse.core.resources.IFolder;
29 import org.eclipse.core.resources.IProject;
30 import org.eclipse.core.resources.IProjectDescription;
31 import org.eclipse.core.resources.IResource;
32 import org.eclipse.core.resources.IncrementalProjectBuilder;
33 import org.eclipse.core.resources.ResourcesPlugin;
34 import org.eclipse.core.runtime.CoreException;
35 import org.eclipse.core.runtime.IPath;
36 import org.eclipse.core.runtime.IProgressMonitor;
37 import org.eclipse.core.runtime.IStatus;
38 import org.eclipse.core.runtime.MultiStatus;
39 import org.eclipse.core.runtime.NullProgressMonitor;
40 import org.eclipse.core.runtime.OperationCanceledException;
41 import org.eclipse.core.runtime.Path;
42 import org.eclipse.core.runtime.Platform;
43 import org.eclipse.core.runtime.Status;
44 import org.eclipse.core.runtime.SubProgressMonitor;
45 import org.eclipse.core.runtime.jobs.Job;
46 import org.eclipse.jdt.core.IClasspathEntry;
47 import org.eclipse.jdt.core.JavaCore;
48 import org.eclipse.jdt.core.JavaModelException;
49 import org.eclipse.jdt.launching.JavaRuntime;
50 import org.eclipse.jdt.launching.environments.IExecutionEnvironmentsManager;
51 import org.eclipse.osgi.service.environment.Constants;
52 import org.eclipse.osgi.service.resolver.BundleDescription;
53 import org.eclipse.osgi.service.resolver.HostSpecification;
54 import org.eclipse.osgi.util.ManifestElement;
55 import org.eclipse.osgi.util.NLS;
56 import org.eclipse.pde.core.build.IBuild;
57 import org.eclipse.pde.core.build.IBuildEntry;
58 import org.eclipse.pde.core.plugin.IFragment;
59 import org.eclipse.pde.core.plugin.IFragmentModel;
60 import org.eclipse.pde.core.plugin.IPluginLibrary;
61 import org.eclipse.pde.core.plugin.IPluginModelBase;
62 import org.eclipse.pde.core.plugin.PluginRegistry;
63 import org.eclipse.pde.internal.core.ClasspathUtilCore;
64 import org.eclipse.pde.internal.core.PDECore;
65 import org.eclipse.pde.internal.core.SourceLocationManager;
66 import org.eclipse.pde.internal.core.build.WorkspaceBuildModel;
67 import org.eclipse.pde.internal.core.bundle.WorkspaceBundleModel;
68 import org.eclipse.pde.internal.core.ibundle.IBundle;
69 import org.eclipse.pde.internal.core.natures.PDE;
70 import org.eclipse.pde.internal.core.util.CoreUtility;
71 import org.eclipse.pde.internal.ui.PDEPlugin;
72 import org.eclipse.pde.internal.ui.PDEUIMessages;
73 import org.eclipse.pde.internal.ui.wizards.plugin.ClasspathComputer;
74 import org.eclipse.team.core.RepositoryProvider;
75 import org.eclipse.team.core.TeamException;
76 import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
77 import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider;
78 import org.osgi.framework.BundleException;
79
80 public class PluginImportOperation extends JarImportOperation {
81
82     public static final int IMPORT_BINARY = 1;
83
84     public static final int IMPORT_BINARY_WITH_LINKS = 2;
85
86     public static final int IMPORT_WITH_SOURCE = 3;
87
88     private IPluginModelBase[] fModels;
89
90     private int fImportType;
91
92     private IImportQuery fReplaceQuery;
93     
94     private Hashtable JavaDoc fProjectClasspaths = new Hashtable JavaDoc();
95
96     private boolean fForceAutobuild;
97
98     private IImportQuery fExecutionQuery;
99
100     public interface IImportQuery {
101         public static final int CANCEL = 0;
102
103         public static final int NO = 1;
104
105         public static final int YES = 2;
106
107         int doQuery(String JavaDoc message);
108     }
109
110     public PluginImportOperation(IPluginModelBase[] models, int importType, IImportQuery replaceQuery, IImportQuery executionQuery) {
111         fModels = models;
112         fImportType = importType;
113         fReplaceQuery = replaceQuery;
114         fExecutionQuery = executionQuery;
115     }
116
117     public PluginImportOperation(IPluginModelBase[] models, int importType, IImportQuery replaceQuery, IImportQuery executionQuery, boolean forceAutobuild) {
118         this(models, importType, replaceQuery, executionQuery);
119         fForceAutobuild = forceAutobuild;
120     }
121
122     public void run(IProgressMonitor monitor) throws CoreException,
123             OperationCanceledException{
124         if (monitor == null) {
125             monitor = new NullProgressMonitor();
126         }
127         monitor.beginTask(PDEUIMessages.ImportWizard_operation_creating, fModels.length + 1);
128         try {
129             MultiStatus multiStatus = new MultiStatus(PDEPlugin.getPluginId(),
130                     IStatus.OK,
131                     PDEUIMessages.ImportWizard_operation_multiProblem,
132                     null);
133
134             for (int i = 0; i < fModels.length; i++) {
135                 try {
136                     importPlugin(fModels[i], new SubProgressMonitor(monitor, 1));
137                 } catch (CoreException e) {
138                     multiStatus.merge(e.getStatus());
139                 }
140                 if (monitor.isCanceled()) {
141                     setClasspaths(new SubProgressMonitor(monitor, 1));
142                     throw new OperationCanceledException();
143                 }
144             }
145             setClasspaths(new SubProgressMonitor(monitor, 1));
146             if (!ResourcesPlugin.getWorkspace().isAutoBuilding() && fForceAutobuild)
147                 runBuildJob();
148             if (!multiStatus.isOK())
149                 throw new CoreException(multiStatus);
150         } finally {
151             monitor.done();
152         }
153     }
154     
155     private void runBuildJob() {
156         Job buildJob = new Job(PDEUIMessages.CompilersConfigurationBlock_building) {
157             public boolean belongsTo(Object JavaDoc family) {
158                 return ResourcesPlugin.FAMILY_AUTO_BUILD == family;
159             }
160
161             protected IStatus run(IProgressMonitor monitor) {
162                 try {
163                     PDEPlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
164                 } catch (CoreException e) {
165                 }
166                 return Status.OK_STATUS;
167             }
168         };
169         buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule());
170         buildJob.schedule();
171     }
172     
173     private void setClasspaths(IProgressMonitor monitor) throws JavaModelException {
174         monitor.beginTask("", fProjectClasspaths.size()); //$NON-NLS-1$
175
Enumeration JavaDoc keys = fProjectClasspaths.keys();
176         while (keys.hasMoreElements()) {
177             IProject project = (IProject)keys.nextElement();
178             IClasspathEntry[] classpath = (IClasspathEntry[])fProjectClasspaths.get(project);
179             monitor.subTask(project.getName());
180             JavaCore.create(project).setRawClasspath(classpath, new SubProgressMonitor(monitor, 1));
181         }
182     }
183
184     private void importPlugin(IPluginModelBase model, IProgressMonitor monitor)
185             throws CoreException {
186         String JavaDoc id = model.getPluginBase().getId();
187         monitor.beginTask(NLS.bind(PDEUIMessages.ImportWizard_operation_creating2, id), 6);
188         try {
189             BundleDescription desc = model.getBundleDescription();
190             if (desc != null) {
191                 IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
192                 String JavaDoc[] envs = desc.getExecutionEnvironments();
193                 boolean found = false;
194                 for (int i = 0; i < envs.length; i++) {
195                     if (manager.getEnvironment(envs[i]) != null) {
196                         found = true;
197                         break;
198                     }
199                 }
200                 if (envs.length > 0 && !found) {
201                     String JavaDoc message = NLS.bind(PDEUIMessages.PluginImportOperation_executionEnvironment, id, envs[0]);
202                     if (!queryExecutionEnvironment(message))
203                         return;
204                 }
205             }
206             
207             IProject project = findProject(id);
208
209             if (project.exists() || new File JavaDoc(project.getParent().getLocation().toFile(), project.getName()).exists()) {
210                 if (!queryReplace(project))
211                     return;
212                 if (RepositoryProvider.isShared(project))
213                     RepositoryProvider.unmap(project);
214                 if (!project.exists())
215                     project.create(new SubProgressMonitor(monitor, 1));
216                 project.delete(true, true, monitor);
217             }
218
219             project.create(monitor);
220             if (!project.isOpen())
221                 project.open(monitor);
222             monitor.worked(1);
223
224             switch (fImportType) {
225                 case IMPORT_BINARY:
226                     importAsBinary(project, model, true, new SubProgressMonitor(monitor, 4));
227                     break;
228                 case IMPORT_BINARY_WITH_LINKS:
229                     if (id.startsWith("org.eclipse.swt") && !isJARd(model)) { //$NON-NLS-1$
230
importAsBinary(project, model, true, monitor);
231                     } else {
232                         importAsBinaryWithLinks(project, model, new SubProgressMonitor(monitor, 4));
233                     }
234                     break;
235                 case IMPORT_WITH_SOURCE:
236                     if (isExempt(model)) {
237                         importAsBinary(project, model, true, new SubProgressMonitor(monitor, 4));
238                     } else {
239                         importAsSource(project, model, new SubProgressMonitor(monitor, 4));
240                     }
241             }
242
243             setProjectDescription(project, model);
244
245             if (project.hasNature(JavaCore.NATURE_ID) && project.findMember(".classpath") == null) //$NON-NLS-1$
246
fProjectClasspaths .put(project, ClasspathComputer.getClasspath(project, model, true));
247         } catch (CoreException e) {
248         } finally {
249             monitor.done();
250         }
251     }
252     
253     private void importAsBinaryWithLinks(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
254         if (isJARd(model)) {
255             extractJARdPlugin(
256                     project,
257                     model,
258                     monitor);
259         } else {
260             File JavaDoc installLocation = new File JavaDoc(model.getInstallLocation());
261             File JavaDoc[] items = installLocation.listFiles();
262             if (items != null) {
263                 monitor.beginTask(PDEUIMessages.PluginImportOperation_linking, items.length + 1);
264                 for (int i = 0; i < items.length; i++) {
265                     File JavaDoc sourceFile = items[i];
266                     String JavaDoc name = sourceFile.getName();
267                     if (sourceFile.isDirectory()) {
268                         project.getFolder(name).createLink(
269                             new Path(sourceFile.getPath()),
270                             IResource.NONE,
271                             new SubProgressMonitor(monitor, 1));
272                     } else {
273                         if (!name.equals(".project")) { //$NON-NLS-1$
274
project.getFile(name).createLink(
275                                 new Path(sourceFile.getPath()),
276                                 IResource.NONE,
277                                 new SubProgressMonitor(monitor, 1));
278                         } else {
279                             // if the binary project with links has a .project file, copy it instead of linking (allows us to edit it)
280
ArrayList JavaDoc filesToImport = new ArrayList JavaDoc(1);
281                             filesToImport.add(sourceFile);
282                             importContent(installLocation, project.getFullPath(), FileSystemStructureProvider.INSTANCE,
283                                     filesToImport, new SubProgressMonitor(monitor, 1));
284                         }
285                     }
286                 }
287             }
288             linkSourceArchives(project, model, new SubProgressMonitor(monitor, 1));
289         }
290         try {
291             RepositoryProvider.map(project, PDECore.BINARY_REPOSITORY_PROVIDER);
292         } catch (TeamException e) {
293         }
294     }
295
296     private void importAsBinary(IProject project, IPluginModelBase model, boolean markAsBinary, IProgressMonitor monitor) throws CoreException {
297         monitor.beginTask("", 3); //$NON-NLS-1$
298
if (isJARd(model)) {
299             extractJARdPlugin(
300                     project,
301                     model,
302                     new SubProgressMonitor(monitor, 2));
303         } else {
304             importContent(
305                     new File JavaDoc(model.getInstallLocation()),
306                     project.getFullPath(),
307                     FileSystemStructureProvider.INSTANCE,
308                     null,
309                     new SubProgressMonitor(monitor, 1));
310             importSourceArchives(
311                     project,
312                     model,
313                     new SubProgressMonitor(monitor, 1));
314             
315             // make sure all libraries have been imported
316
// if any are missing, check in fragments
317
IFragment[] fragments = getFragmentsFor(model);
318             IPluginLibrary[] libraries = model.getPluginBase().getLibraries();
319             
320             for (int i = 0; i < libraries.length; i++) {
321                 String JavaDoc libraryName = libraries[i].getName();
322                 if (ClasspathUtilCore.containsVariables(libraryName) &&
323                         !project.exists(new Path(ClasspathUtilCore.expandLibraryName(libraryName)))) {
324                     for (int j = 0; j < fragments.length; j++) {
325                         importJarFromFragment(project, fragments[j], libraryName);
326                         importSourceFromFragment(project, fragments[j], libraryName);
327                     }
328                 }
329             }
330         }
331         if (markAsBinary) {
332             project.setPersistentProperty(
333                     PDECore.EXTERNAL_PROJECT_PROPERTY,
334                     PDECore.BINARY_PROJECT_VALUE);
335             importAdditionalResources(project, model, new SubProgressMonitor(monitor, 1));
336         } else {
337             monitor.done();
338         }
339     }
340
341     private void importAsSource(IProject project, IPluginModelBase model, SubProgressMonitor monitor) throws CoreException {
342         monitor.beginTask("", 4); //$NON-NLS-1$
343
importAsBinary(project, model, false, new SubProgressMonitor(monitor, 2));
344         List JavaDoc list = importAdditionalResources(project, model, new SubProgressMonitor(monitor, 1));
345         WorkspaceBuildModel buildModel = new WorkspaceBuildModel(project.getFile("build.properties")); //$NON-NLS-1$
346
if (!isJARd(model) || containsCode(new File JavaDoc(model.getInstallLocation()))) {
347             String JavaDoc[] libraries = getLibraryNames(model, false);
348             if (libraries.length == 0)
349                 libraries = new String JavaDoc[]{"."}; //$NON-NLS-1$
350
for (int i = 0; i < libraries.length; i++) {
351                 if (ClasspathUtilCore.containsVariables(libraries[i]))
352                     continue;
353                 String JavaDoc name = ClasspathUtilCore.expandLibraryName(libraries[i]);
354                 IPath libraryPath = (name.equals(".") && isJARd(model)) //$NON-NLS-1$
355
? new Path(new File JavaDoc(model.getInstallLocation()).getName())
356                                         : new Path(name);
357                 IResource jarFile = project.findMember(libraryPath);
358                 if (jarFile != null) {
359                     String JavaDoc srcName = ClasspathUtilCore.getSourceZipName(libraryPath.lastSegment());
360                     IResource srcZip = jarFile.getProject().findMember(srcName);
361                     // srcZip == null if plug-in has embedded source
362
// if it jarred, all necessary files already in src folder
363
if (srcZip == null && libraries[i].equals(".") && !isJARd(model)) //$NON-NLS-1$
364
// if src does not exist (and returns null), then must not be plug-in with embedded source
365
srcZip = jarFile.getProject().findMember("src"); //$NON-NLS-1$
366
if (srcZip != null) {
367                         String JavaDoc jarName = libraries[i].equals(".") ? "" : libraryPath.removeFileExtension().lastSegment(); //$NON-NLS-1$ //$NON-NLS-2$
368
String JavaDoc 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$
369
IFolder dest = jarFile.getProject().getFolder(folder);
370                         if (!dest.exists()) {
371                             dest.create(true, true, null);
372                         }
373                         if (srcZip instanceof IFile) {
374                             extractZipFile(srcZip.getLocation().toFile(), dest.getFullPath(), new SubProgressMonitor(monitor, 1));
375                             srcZip.delete(true, null);
376                         } else
377                             monitor.worked(1);
378
379                         if (jarFile instanceof IFile) {
380                             if (isJARd(model)) {
381                                 extractJavaResources(jarFile.getLocation().toFile(), dest, new SubProgressMonitor(monitor, 1));
382                             } else {
383                                 extractResources(jarFile.getLocation().toFile(), dest, new SubProgressMonitor(monitor, 1));
384                             }
385                             jarFile.delete(true, null);
386                         } else {
387                             copyAndDeleteBinaryContents((IContainer)jarFile, dest, new SubProgressMonitor(monitor, 1));
388                         }
389                     }
390                 } else if (name.equals(".") && project.getFolder("src").exists()) { //$NON-NLS-1$ //$NON-NLS-2$
391
addBuildEntry(buildModel, "source..", "src/"); //$NON-NLS-1$ //$NON-NLS-2$
392
}
393             }
394         }
395         configureBinIncludes(buildModel, model, project);
396         if (list.size() > 0)
397             configureSrcIncludes(buildModel, list);
398         buildModel.save();
399     }
400     
401     private void copyAndDeleteBinaryContents(IContainer srcFolder, IFolder dest, IProgressMonitor monitor) {
402         try {
403             // get all the folders for which we want to search
404
IResource[] children = dest.members();
405             ArrayList JavaDoc validFolders = new ArrayList JavaDoc();
406             for (int i = 0; i < children.length; i++)
407                 if (children[i] instanceof IFolder) {
408                     String JavaDoc folderName = children[i].getName();
409                     IResource folder = srcFolder.findMember(folderName);
410                     if (folder != null && folder instanceof IFolder)
411                         validFolders.add(folder);
412                 }
413             
414             monitor.beginTask(new String JavaDoc(), validFolders.size());
415             
416             ListIterator JavaDoc li = validFolders.listIterator();
417             while (li.hasNext()) {
418                 IFolder folder = (IFolder)li.next();
419                 int pathSegments = folder.getProjectRelativePath().segmentCount() - 1;
420                 Stack JavaDoc stack = new Stack JavaDoc();
421                 IResource[] resources = folder.members();
422                 for (int i = 0; i < resources.length; i++)
423                     stack.push(resources[i]);
424                 
425                 while (!stack.isEmpty()) {
426                     IResource res = (IResource) stack.pop();
427                     if (res instanceof IFile) {
428                         if (!res.getName().endsWith(".class")) { //$NON-NLS-1$
429
String JavaDoc pathName = res.getProjectRelativePath().removeFirstSegments(pathSegments).toString();
430                             IFile destFile = dest.getFile(pathName);
431                             if(!destFile.getParent().exists()) {
432                                 CoreUtility.createFolder((IFolder)destFile.getParent());
433                             }
434                             // file might exist if previous project was deleted without removing underlying resources
435
if (destFile.exists())
436                                 destFile.delete(true, null);
437                             res.move(destFile.getFullPath(), true, null);
438                         }
439                     } else {
440                         resources = ((IFolder)res).members();
441                         for (int i = 0; i < resources.length; i++)
442                             stack.push(resources[i]);
443                     }
444                 }
445                 folder.delete(true, null);
446                 monitor.worked(1);
447             }
448         } catch (CoreException e) {
449         }
450     }
451
452     private List JavaDoc importAdditionalResources(IProject project, IPluginModelBase model,
453             SubProgressMonitor monitor) throws CoreException {
454         SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
455         File JavaDoc location = manager.findSourcePlugin(model.getPluginBase());
456         File JavaDoc[] children = location == null ? null : location.listFiles();
457         ArrayList JavaDoc list = new ArrayList JavaDoc();
458         if (children != null) {
459             for (int i = 0; i < children.length; i++) {
460                 String JavaDoc name = children[i].getName();
461                 if (!project.exists(new Path(name)) && !"src.zip".equals(name)) { //$NON-NLS-1$
462
list.add(children[i]);
463                 }
464             }
465             
466             importContent(
467                     location,
468                     project.getFullPath(),
469                     FileSystemStructureProvider.INSTANCE,
470                     list,
471                     monitor);
472         }
473         return list;
474     }
475
476     private void configureBinIncludes(WorkspaceBuildModel buildModel, IPluginModelBase model, IProject project) throws CoreException {
477         IBuild build = buildModel.getBuild(true);
478         IBuildEntry entry = build.getEntry("bin.includes"); //$NON-NLS-1$
479
HashMap JavaDoc libraryDirs = getSourceDirectories(build);
480         if (entry == null) {
481             entry = buildModel.getFactory().createEntry("bin.includes"); //$NON-NLS-1$
482
File JavaDoc location = new File JavaDoc(model.getInstallLocation());
483             if (location.isDirectory()) {
484                 File JavaDoc[] files = location.listFiles();
485                 for (int i = 0; i < files.length; i++) {
486                     String JavaDoc token = files[i].getName();
487                     if ((project.findMember(token) == null) && (build.getEntry(IBuildEntry.JAR_PREFIX + token) == null))
488                             continue;
489                     if (files[i].isDirectory()) {
490                         token = token + "/"; //$NON-NLS-1$
491
if (libraryDirs.containsKey(token))
492                             token = libraryDirs.get(token).toString();
493                     }
494                     entry.addToken(token);
495                 }
496             } else {
497                 String JavaDoc[] tokens = getTopLevelResources(location);
498                 for (int i = 0; i < tokens.length; i++) {
499                     IResource res = project.findMember(tokens[i]);
500                     if ((res == null) && (build.getEntry(IBuildEntry.JAR_PREFIX + tokens[i]) == null))
501                         continue;
502                     if ((res instanceof IFolder) && (libraryDirs.containsKey(tokens[i])))
503                         continue;
504                     entry.addToken(tokens[i]);
505                 }
506             }
507             buildModel.getBuild().add(entry);
508         }
509     }
510     
511     private HashMap JavaDoc getSourceDirectories(IBuild build) {
512         HashMap JavaDoc set = new HashMap JavaDoc();
513         IBuildEntry[] entries = build.getBuildEntries();
514         for (int i = 0; i < entries.length; i++) {
515             String JavaDoc name = entries[i].getName();
516             if (name.startsWith(IBuildEntry.JAR_PREFIX)) {
517                 name = name.substring(7);
518                 String JavaDoc[] tokens = entries[i].getTokens();
519                 for (int j = 0; j < tokens.length; j++) {
520                     set.put(tokens[j], name);
521                 }
522             }
523         }
524         return set;
525     }
526
527     private void configureSrcIncludes(WorkspaceBuildModel buildModel, List JavaDoc list) throws CoreException {
528         IBuildEntry entry = buildModel.getBuild(true).getEntry("src.includes"); //$NON-NLS-1$
529
if (entry == null) {
530             entry = buildModel.getFactory().createEntry("src.includes"); //$NON-NLS-1$
531
for (int i = 0; i < list.size(); i++) {
532                 File JavaDoc location = (File JavaDoc)list.get(i);
533                 String JavaDoc token = location.getName();
534                 if (location.isDirectory())
535                     token += "/"; //$NON-NLS-1$
536
entry.addToken(token);
537             }
538             buildModel.getBuild().add(entry);
539         }
540     }
541
542     private String JavaDoc addBuildEntry(WorkspaceBuildModel model, String JavaDoc key, String JavaDoc value) throws CoreException {
543         IBuild build = model.getBuild(true);
544         IBuildEntry entry = build.getEntry(key);
545         if (entry == null) {
546             entry = model.getFactory().createEntry(key);
547             entry.addToken(value);
548             build.add(entry);
549         }
550         String JavaDoc[] tokens = entry.getTokens();
551         return (tokens.length > 0) ? tokens[0] : "src/"; //$NON-NLS-1$
552
}
553
554     private void linkSourceArchives(IProject project, IPluginModelBase model,
555             IProgressMonitor monitor) throws CoreException {
556
557         String JavaDoc[] libraries = getLibraryNames(model, true);
558         monitor.beginTask(PDEUIMessages.ImportWizard_operation_copyingSource,
559                 libraries.length);
560
561         SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
562         for (int i = 0; i < libraries.length; i++) {
563             String JavaDoc zipName = ClasspathUtilCore.getSourceZipName(libraries[i]);
564             IPath path = new Path(zipName);
565             if (project.findMember(path) == null) {
566                 IPath srcPath = manager.findSourcePath(model.getPluginBase(), path);
567                 if (srcPath != null) {
568                     if ("src.zip".equals(zipName) && isJARd(model)) { //$NON-NLS-1$
569
path = new Path(ClasspathUtilCore.getSourceZipName(new File JavaDoc(model
570                                 .getInstallLocation()).getName()));
571                     }
572                     IFile zipFile = project.getFile(path.lastSegment());
573                     if (!zipFile.exists()) {
574                         zipFile.createLink(
575                                 srcPath,
576                                 IResource.NONE,
577                                 new SubProgressMonitor(monitor, 1));
578                     }
579                 }
580             }
581             monitor.worked(1);
582         }
583         monitor.done();
584     }
585
586     private void importSourceArchives(IProject project, IPluginModelBase model, IProgressMonitor monitor)
587             throws CoreException {
588         
589         String JavaDoc[] libraries = getLibraryNames(model, true);
590         monitor.beginTask(PDEUIMessages.ImportWizard_operation_copyingSource, libraries.length);
591
592         SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
593         for (int i = 0; i < libraries.length; i++) {
594             String JavaDoc zipName = ClasspathUtilCore.getSourceZipName(libraries[i]);
595             IPath path = new Path(zipName);
596             if (project.findMember(path) == null) {
597                 IPath srcPath = manager.findSourcePath(model.getPluginBase(), path);
598                 if (srcPath != null) {
599                     if ("src.zip".equals(zipName) && isJARd(model)) { //$NON-NLS-1$
600
path = new Path(ClasspathUtilCore.getSourceZipName(new File JavaDoc(model.getInstallLocation()).getName()));
601                     }
602                     importArchive(project, new File JavaDoc(srcPath.toOSString()), path);
603                 }
604             }
605             monitor.worked(1);
606         }
607         monitor.done();
608     }
609     
610     private String JavaDoc[] getLibraryNames(IPluginModelBase model, boolean expand) {
611         IPluginLibrary[] libraries = model.getPluginBase().getLibraries();
612         ArrayList JavaDoc list = new ArrayList JavaDoc();
613         for (int i = 0; i < libraries.length; i++) {
614             if (expand)
615                 list.add(ClasspathUtilCore.expandLibraryName(libraries[i].getName()));
616             else
617                 list.add(libraries[i].getName());
618         }
619         if (libraries.length == 0 && isJARd(model))
620             list.add("."); //$NON-NLS-1$
621
return (String JavaDoc[])list.toArray(new String JavaDoc[list.size()]);
622     }
623     
624     private void extractJARdPlugin(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException {
625         ZipFile JavaDoc zipFile = null;
626         try {
627             zipFile = new ZipFile JavaDoc(model.getInstallLocation());
628             ZipFileStructureProvider provider = new ZipFileStructureProvider(zipFile);
629             if (!containsCode(provider)) {
630                 extractZipFile(new File JavaDoc(model.getInstallLocation()), project.getFullPath(), monitor);
631                 return;
632             }
633             ArrayList JavaDoc collected = new ArrayList JavaDoc();
634             collectNonJavaResources(provider, provider.getRoot(), collected);
635             importContent(provider.getRoot(), project.getFullPath(), provider, collected, monitor);
636
637             File JavaDoc file = new File JavaDoc(model.getInstallLocation());
638             if (hasEmbeddedSource(provider) && fImportType == IMPORT_WITH_SOURCE) {
639                 collected = new ArrayList JavaDoc();
640                 collectJavaFiles(provider, provider.getRoot(), collected);
641                 importContent(provider.getRoot(), project.getFullPath(), provider, collected, monitor);
642                 collected = new ArrayList JavaDoc();
643                 collectJavaResources(provider, provider.getRoot(), collected);
644                 importContent(provider.getRoot(), project.getFullPath().append("src"), provider, collected, monitor); //$NON-NLS-1$
645
} else {
646                 if (fImportType == IMPORT_BINARY_WITH_LINKS) {
647                      project.getFile(file.getName()).createLink(
648                         new Path(file.getAbsolutePath()),
649                         IResource.NONE,
650                         null);
651                 } else {
652                     importArchive(project, file, new Path(file.getName()));
653                 }
654                 if (!hasEmbeddedSource(provider)) {
655                     if (fImportType == IMPORT_BINARY_WITH_LINKS) {
656                         linkSourceArchives(
657                                 project,
658                                 model,
659                                 new SubProgressMonitor(monitor, 1));
660                     } else {
661                         importSourceArchives(
662                                 project,
663                                 model,
664                                 new SubProgressMonitor(monitor, 1));
665                     }
666                 }
667             }
668             if (fImportType != IMPORT_WITH_SOURCE) {
669                 modifyBundleClasspathHeader(project, model);
670             } else {
671                 removeSignedHeaders(project);
672             }
673             setPermissions(model, project);
674         } catch (IOException JavaDoc e) {
675             IStatus status = new Status(IStatus.ERROR, PDEPlugin.getPluginId(),
676                     IStatus.ERROR, e.getMessage(), e);
677             throw new CoreException(status);
678         } finally {
679             if (zipFile != null) {
680                 try {
681                     zipFile.close();
682                 } catch (IOException JavaDoc e) {
683                 }
684             }
685         }
686     }
687     
688     private void modifyBundleClasspathHeader(IProject project, IPluginModelBase base) {
689         IFile file = project.getFile(JarFile.MANIFEST_NAME);
690         if (file.exists()) {
691             WorkspaceBundleModel bmodel = new WorkspaceBundleModel(file);
692             IBundle bundle = bmodel.getBundle();
693             String JavaDoc classpath = bundle.getHeader(org.osgi.framework.Constants.BUNDLE_CLASSPATH);
694             if (classpath == null) {
695                 bundle.setHeader(org.osgi.framework.Constants.BUNDLE_CLASSPATH,
696                         ClasspathUtilCore.getFilename(base));
697             } else {
698                 try {
699                     ManifestElement[] elements = ManifestElement.parseHeader(org.osgi.framework.Constants.BUNDLE_CLASSPATH, classpath);
700                     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
701                     for (int i = 0; i < elements.length; i++) {
702                         if (buffer.length() > 0) {
703                             buffer.append(","); //$NON-NLS-1$
704
buffer.append(System.getProperty("line.separator")); //$NON-NLS-1$
705
buffer.append(" "); //$NON-NLS-1$
706
}
707                         if (elements[i].getValue().equals(".")) //$NON-NLS-1$
708
buffer.append(ClasspathUtilCore.getFilename(base));
709                         else
710                             buffer.append(elements[i].getValue());
711                     }
712                     bundle.setHeader(org.osgi.framework.Constants.BUNDLE_CLASSPATH, buffer.toString());
713                 } catch (BundleException e) {
714                 }
715             }
716             bmodel.save();
717         }
718     }
719     
720     private void removeSignedHeaders(IProject project) {
721         IFile file = project.getFile(JarFile.MANIFEST_NAME);
722         if (!file.exists())
723             return;
724         WorkspaceBundleModel model = new WorkspaceBundleModel(file);
725         model.save();
726     }
727
728     private IProject findProject(String JavaDoc id) {
729         IPluginModelBase model = PluginRegistry.findModel(id);
730         if (model != null) {
731             IResource resource = model.getUnderlyingResource();
732             if (resource != null)
733                 return resource.getProject();
734         }
735         return PDEPlugin.getWorkspace().getRoot().getProject(id);
736     }
737
738     private boolean queryReplace(IProject project) throws OperationCanceledException {
739         switch (fReplaceQuery.doQuery(
740                 NLS.bind(PDEUIMessages.ImportWizard_messages_exists, project.getName()))) {
741             case IImportQuery.CANCEL:
742                 throw new OperationCanceledException();
743             case IImportQuery.NO:
744                 return false;
745         }
746         return true;
747     }
748     
749     private boolean queryExecutionEnvironment(String JavaDoc message) throws OperationCanceledException {
750         switch (fExecutionQuery.doQuery(message)) {
751             case IImportQuery.CANCEL:
752                 throw new OperationCanceledException();
753             case IImportQuery.NO:
754                 return false;
755         }
756         return true;
757     }
758     
759     private void setProjectDescription(IProject project, IPluginModelBase model)
760             throws CoreException {
761         IProjectDescription desc = project.getDescription();
762         if (!desc.hasNature(PDE.PLUGIN_NATURE))
763             CoreUtility.addNatureToProject(project, PDE.PLUGIN_NATURE, null);
764         if (needsJavaNature(project, model) && !desc.hasNature(JavaCore.NATURE_ID))
765             CoreUtility.addNatureToProject(project, JavaCore.NATURE_ID, null);
766     }
767
768     private boolean needsJavaNature(IProject project, IPluginModelBase model) {
769         if (model.getPluginBase().getLibraries().length > 0)
770             return true;
771         
772         BundleDescription desc = model.getBundleDescription();
773         if (desc != null) {
774             if (desc.getExportPackages().length > 0)
775                 return true;
776             if (desc.getRequiredBundles().length > 0)
777                 return true;
778             if (desc.getImportPackages().length > 0)
779                 return true;
780         }
781         return false;
782     }
783     
784     private boolean isExempt(IPluginModelBase model) {
785         String JavaDoc id = model.getPluginBase().getId();
786         if ("org.apache.ant".equals(id) //$NON-NLS-1$
787
|| "org.eclipse.osgi.util".equals(id) //$NON-NLS-1$
788
|| "org.eclipse.osgi.services".equals(id) //$NON-NLS-1$
789
|| "org.eclipse.core.runtime.compatibility.registry".equals(id)) //$NON-NLS-1$
790
return true;
791         
792         if ("org.eclipse.swt".equals(id) && !isJARd(model)) //$NON-NLS-1$
793
return true;
794         return false;
795     }
796
797     private boolean isJARd(IPluginModelBase model) {
798         return new File JavaDoc(model.getInstallLocation()).isFile();
799     }
800     
801     private void setPermissions(IPluginModelBase model, IProject project) {
802         try {
803             if (!Platform.getOS().equals(Constants.OS_WIN32) && model instanceof IFragmentModel) {
804                 IFragment fragment = ((IFragmentModel)model).getFragment();
805                 if ("org.eclipse.swt".equals(fragment.getPluginId())) { //$NON-NLS-1$
806
IResource[] children = project.members();
807                     for (int i = 0; i < children.length; i++) {
808                         if (children[i] instanceof IFile && isInterestingResource(children[i].getName())) {
809                             Runtime.getRuntime().exec(new String JavaDoc[] {"chmod", "755", children[i].getLocation().toOSString()}).waitFor(); //$NON-NLS-1$ //$NON-NLS-2$
810
}
811                     }
812                 }
813             }
814         } catch (CoreException e) {
815         } catch (InterruptedException JavaDoc e) {
816         } catch (IOException JavaDoc e) {
817         }
818     }
819     
820     private boolean isInterestingResource(String JavaDoc name) {
821         return name.endsWith(".jnilib") //$NON-NLS-1$
822
|| name.endsWith(".sl") //$NON-NLS-1$
823
|| name.endsWith(".a") //$NON-NLS-1$
824
|| name.indexOf(".so") != -1; //$NON-NLS-1$
825
}
826     
827     private IFragment[] getFragmentsFor(IPluginModelBase model) {
828         ArrayList JavaDoc result = new ArrayList JavaDoc();
829         for (int i = 0; i < fModels.length; i++) {
830             if (fModels[i] instanceof IFragmentModel) {
831                 HostSpecification spec = fModels[i].getBundleDescription().getHost();
832                 BundleDescription host = spec == null ? null : (BundleDescription)spec.getSupplier();
833                 if (model.getBundleDescription().equals(host)) {
834                     result.add(((IFragmentModel)fModels[i]).getFragment());
835                 }
836             }
837         }
838         return (IFragment[])result.toArray(new IFragment[result.size()]);
839     }
840     
841     private void importJarFromFragment(IProject project, IFragment fragment, String JavaDoc name)
842         throws CoreException {
843         IPath jarPath = new Path(ClasspathUtilCore.expandLibraryName(name));
844         File JavaDoc jar =
845             new File JavaDoc(fragment.getModel().getInstallLocation(), jarPath.toString());
846         if (jar.exists()) {
847             importArchive(project, jar, jarPath);
848         }
849     }
850     
851     private void importSourceFromFragment(IProject project, IFragment fragment, String JavaDoc name)
852         throws CoreException {
853         IPath jarPath = new Path(ClasspathUtilCore.expandLibraryName(name));
854         IPath srcPath = new Path(ClasspathUtilCore.getSourceZipName(jarPath.toString()));
855         SourceLocationManager manager = PDECore.getDefault().getSourceLocationManager();
856         File JavaDoc srcFile = manager.findSourceFile(fragment, srcPath);
857         if (srcFile != null) {
858             importArchive(project, srcFile, srcPath);
859         }
860     }
861
862     protected void collectNonJavaResources(ZipFileStructureProvider provider,
863             Object JavaDoc element, ArrayList JavaDoc collected) {
864         super.collectNonJavaResources(provider, element, collected);
865         if (fImportType != IMPORT_WITH_SOURCE)
866             return;
867         // filter the resources we get back to include only relevant resource files
868
ListIterator JavaDoc li = collected.listIterator();
869         while (li.hasNext()) {
870             ZipEntry JavaDoc ze = (ZipEntry JavaDoc)li.next();
871             String JavaDoc name = ze.getName();
872             // filter out signature files - bug 175756
873
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$
874
li.remove();
875         }
876     }
877     
878 }
879
Popular Tags