KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > refactoring > binary > BinaryRefactoringHistoryWizard


1 /*******************************************************************************
2  * Copyright (c) 2005, 2006 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.jdt.internal.ui.refactoring.binary;
12
13 import java.net.URI JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.Arrays JavaDoc;
16 import java.util.Collection JavaDoc;
17 import java.util.HashSet JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.jar.JarFile JavaDoc;
20
21 import org.eclipse.core.filesystem.EFS;
22 import org.eclipse.core.filesystem.IFileStore;
23 import org.eclipse.core.filesystem.URIUtil;
24
25 import org.eclipse.core.runtime.Assert;
26 import org.eclipse.core.runtime.CoreException;
27 import org.eclipse.core.runtime.IAdaptable;
28 import org.eclipse.core.runtime.IPath;
29 import org.eclipse.core.runtime.IProgressMonitor;
30 import org.eclipse.core.runtime.SubProgressMonitor;
31
32 import org.eclipse.core.resources.IFolder;
33 import org.eclipse.core.resources.IResource;
34 import org.eclipse.core.resources.IWorkspaceRoot;
35 import org.eclipse.core.resources.IWorkspaceRunnable;
36 import org.eclipse.core.resources.ResourcesPlugin;
37
38 import org.eclipse.ltk.core.refactoring.Change;
39 import org.eclipse.ltk.core.refactoring.Refactoring;
40 import org.eclipse.ltk.core.refactoring.RefactoringContribution;
41 import org.eclipse.ltk.core.refactoring.RefactoringCore;
42 import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
43 import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
44 import org.eclipse.ltk.core.refactoring.RefactoringStatus;
45 import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
46 import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
47 import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
48 import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
49 import org.eclipse.ltk.ui.refactoring.history.RefactoringHistoryWizard;
50
51 import org.eclipse.jdt.core.IClasspathEntry;
52 import org.eclipse.jdt.core.ICompilationUnit;
53 import org.eclipse.jdt.core.IJavaElement;
54 import org.eclipse.jdt.core.IJavaModel;
55 import org.eclipse.jdt.core.IJavaProject;
56 import org.eclipse.jdt.core.IPackageFragment;
57 import org.eclipse.jdt.core.IPackageFragmentRoot;
58 import org.eclipse.jdt.core.JavaCore;
59 import org.eclipse.jdt.core.JavaModelException;
60 import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor;
61
62 import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringContribution;
63 import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptor;
64 import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments;
65 import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
66 import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext;
67 import org.eclipse.jdt.internal.corext.refactoring.binary.SourceCreationOperation;
68 import org.eclipse.jdt.internal.corext.refactoring.binary.StubCreationOperation;
69 import org.eclipse.jdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
70 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
71 import org.eclipse.jdt.internal.corext.util.Messages;
72
73 import org.eclipse.jdt.internal.ui.JavaPlugin;
74 import org.eclipse.jdt.internal.ui.jarimport.JarImportMessages;
75 import org.eclipse.jdt.internal.ui.util.CoreUtility;
76
77 /**
78  * Partial implementation of a refactoring history wizard which creates stubs
79  * from a binary package fragment root while refactoring.
80  *
81  * @since 3.2
82  */

83 public abstract class BinaryRefactoringHistoryWizard extends RefactoringHistoryWizard {
84
85     /** The meta-inf fragment */
86     private static final String JavaDoc META_INF_FRAGMENT= JarFile.MANIFEST_NAME.substring(0, JarFile.MANIFEST_NAME.indexOf('/'));
87
88     /** The temporary linked source folder */
89     private static final String JavaDoc SOURCE_FOLDER= ".src"; //$NON-NLS-1$
90

91     /** The temporary stubs folder */
92     private static final String JavaDoc STUB_FOLDER= ".stubs"; //$NON-NLS-1$
93

94     /**
95      * Updates the new classpath with exclusion patterns for the specified path.
96      *
97      * @param entries
98      * the classpath entries
99      * @param path
100      * the path
101      */

102     private static void addExclusionPatterns(final List JavaDoc entries, final IPath path) {
103         for (int index= 0; index < entries.size(); index++) {
104             final IClasspathEntry entry= (IClasspathEntry) entries.get(index);
105             if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && entry.getPath().isPrefixOf(path)) {
106                 final IPath[] patterns= entry.getExclusionPatterns();
107                 if (!JavaModelUtil.isExcludedPath(path, patterns)) {
108                     final IPath[] filters= new IPath[patterns.length + 1];
109                     System.arraycopy(patterns, 0, filters, 0, patterns.length);
110                     filters[patterns.length]= path.removeFirstSegments(entry.getPath().segmentCount()).addTrailingSeparator();
111                     entries.set(index, JavaCore.newSourceEntry(entry.getPath(), filters, entry.getOutputLocation()));
112                 }
113             }
114         }
115     }
116
117     /**
118      * Checks whether the archive referenced by the package fragment root is not
119      * shared with multiple java projects in the workspace.
120      *
121      * @param root
122      * the package fragment root
123      * @param monitor
124      * the progress monitor to use
125      * @return the status of the operation
126      */

127     private static RefactoringStatus checkPackageFragmentRoots(final IPackageFragmentRoot root, final IProgressMonitor monitor) {
128         final RefactoringStatus status= new RefactoringStatus();
129         try {
130             monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 100);
131             final IWorkspaceRoot workspace= ResourcesPlugin.getWorkspace().getRoot();
132             if (workspace != null) {
133                 final IJavaModel model= JavaCore.create(workspace);
134                 if (model != null) {
135                     try {
136                         final URI JavaDoc uri= getLocationURI(root.getRawClasspathEntry());
137                         if (uri != null) {
138                             final IJavaProject[] projects= model.getJavaProjects();
139                             final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
140                             try {
141                                 subMonitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, projects.length * 100);
142                                 for (int index= 0; index < projects.length; index++) {
143                                     final IPackageFragmentRoot[] roots= projects[index].getPackageFragmentRoots();
144                                     final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
145                                     try {
146                                         subsubMonitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, roots.length);
147                                         for (int offset= 0; offset < roots.length; offset++) {
148                                             final IPackageFragmentRoot current= roots[offset];
149                                             if (!current.equals(root) && current.getKind() == IPackageFragmentRoot.K_BINARY) {
150                                                 final IClasspathEntry entry= current.getRawClasspathEntry();
151                                                 if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
152                                                     final URI JavaDoc location= getLocationURI(entry);
153                                                     if (uri.equals(location))
154                                                         status.addFatalError(Messages.format(JarImportMessages.JarImportWizard_error_shared_jar, new String JavaDoc[] { current.getJavaProject().getElementName() }));
155                                                 }
156                                             }
157                                             subsubMonitor.worked(1);
158                                         }
159                                     } finally {
160                                         subsubMonitor.done();
161                                     }
162                                 }
163                             } finally {
164                                 subMonitor.done();
165                             }
166                         }
167                     } catch (CoreException exception) {
168                         status.addError(exception.getLocalizedMessage());
169                     }
170                 }
171             }
172         } finally {
173             monitor.done();
174         }
175         return status;
176     }
177
178     /**
179      * Configures the classpath of the project before refactoring.
180      *
181      * @param project
182      * the java project
183      * @param root
184      * the package fragment root to refactor
185      * @param folder
186      * the temporary source folder
187      * @param monitor
188      * the progress monitor to use
189      * @throws IllegalStateException
190      * if the plugin state location does not exist
191      * @throws CoreException
192      * if an error occurs while configuring the class path
193      */

194     private static void configureClasspath(final IJavaProject project, final IPackageFragmentRoot root, final IFolder folder, final IProgressMonitor monitor) throws IllegalStateException JavaDoc, CoreException {
195         try {
196             monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 200);
197             final IClasspathEntry entry= root.getRawClasspathEntry();
198             final IClasspathEntry[] entries= project.getRawClasspath();
199             final List JavaDoc list= new ArrayList JavaDoc();
200             list.addAll(Arrays.asList(entries));
201             final IFileStore store= EFS.getLocalFileSystem().getStore(JavaPlugin.getDefault().getStateLocation().append(STUB_FOLDER).append(project.getElementName()));
202             if (store.fetchInfo(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).exists())
203                 store.delete(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
204             store.mkdir(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
205             folder.createLink(store.toURI(), IResource.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
206             addExclusionPatterns(list, folder.getFullPath());
207             for (int index= 0; index < entries.length; index++) {
208                 if (entries[index].equals(entry))
209                     list.add(index, JavaCore.newSourceEntry(folder.getFullPath()));
210             }
211             project.setRawClasspath((IClasspathEntry[]) list.toArray(new IClasspathEntry[list.size()]), false, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
212         } finally {
213             monitor.done();
214         }
215     }
216
217     /**
218      * Returns the location URI of the classpath entry
219      *
220      * @param entry
221      * the classpath entry
222      * @return the location URI
223      */

224     public static URI JavaDoc getLocationURI(final IClasspathEntry entry) {
225         IPath path= null;
226         if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE)
227             path= JavaCore.getResolvedVariablePath(entry.getPath());
228         else
229             path= entry.getPath();
230         final IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
231         URI JavaDoc location= null;
232         if (root.exists(path)) {
233             location= root.getFile(path).getRawLocationURI();
234         } else
235             location= URIUtil.toURI(path);
236         return location;
237     }
238
239     /** Is auto build enabled? */
240     protected boolean fAutoBuild= true;
241
242     /** Has the wizard been cancelled? */
243     protected boolean fCancelled= false;
244
245     /** The current refactoring arguments, or <code>null</code> */
246     protected RefactoringArguments fCurrentArguments= null;
247
248     /** The current refactoring to be initialized, or <code>null</code> */
249     protected IScriptableRefactoring fCurrentRefactoring= null;
250
251     /** The java project or <code>null</code> */
252     protected IJavaProject fJavaProject= null;
253
254     /**
255      * The packages which already have been processed (element type:
256      * &lt;IPackageFragment&gt;)
257      */

258     protected final Collection JavaDoc fProcessedFragments= new HashSet JavaDoc();
259
260     /** The temporary source folder, or <code>null</code> */
261     protected IFolder fSourceFolder= null;
262
263     /**
264      * Creates a new stub refactoring history wizard.
265      *
266      * @param overview
267      * <code>true</code> to show an overview of the refactorings,
268      * <code>false</code> otherwise
269      * @param caption
270      * the wizard caption
271      * @param title
272      * the wizard title
273      * @param description
274      * the wizard description
275      */

276     protected BinaryRefactoringHistoryWizard(final boolean overview, final String JavaDoc caption, final String JavaDoc title, final String JavaDoc description) {
277         super(overview, caption, title, description);
278     }
279
280     /**
281      * Creates a new stub refactoring history wizard.
282      *
283      * @param caption
284      * the wizard caption
285      * @param title
286      * the wizard title
287      * @param description
288      * the wizard description
289      */

290     protected BinaryRefactoringHistoryWizard(final String JavaDoc caption, final String JavaDoc title, final String JavaDoc description) {
291         super(caption, title, description);
292     }
293
294     /**
295      * {@inheritDoc}
296      */

297     protected RefactoringStatus aboutToPerformHistory(final IProgressMonitor monitor) {
298         final RefactoringStatus status= new RefactoringStatus();
299         try {
300             fJavaProject= null;
301             fSourceFolder= null;
302             fProcessedFragments.clear();
303             monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 520);
304             status.merge(super.aboutToPerformHistory(new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
305             if (!status.hasFatalError()) {
306                 final IPackageFragmentRoot root= getPackageFragmentRoot();
307                 if (root != null) {
308                     status.merge(checkPackageFragmentRoots(root, new SubProgressMonitor(monitor, 90, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
309                     if (!status.hasFatalError()) {
310                         status.merge(checkSourceAttachmentRefactorings(new SubProgressMonitor(monitor, 20, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
311                         if (!status.hasFatalError()) {
312                             final IJavaProject project= root.getJavaProject();
313                             if (project != null) {
314                                 final IFolder folder= project.getProject().getFolder(SOURCE_FOLDER + String.valueOf(System.currentTimeMillis()));
315                                 try {
316                                     fAutoBuild= CoreUtility.enableAutoBuild(false);
317                                     final RefactoringHistory history= getRefactoringHistory();
318                                     if (history != null && !history.isEmpty())
319                                         configureClasspath(project, root, folder, new SubProgressMonitor(monitor, 300, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
320                                 } catch (CoreException exception) {
321                                     status.merge(RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage()));
322                                     try {
323                                         project.setRawClasspath(project.readRawClasspath(), false, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
324                                     } catch (CoreException throwable) {
325                                         JavaPlugin.log(throwable);
326                                     }
327                                 } finally {
328                                     if (!status.hasFatalError()) {
329                                         fJavaProject= project;
330                                         fSourceFolder= folder;
331                                     }
332                                 }
333                             }
334                         }
335                     }
336                 }
337             }
338         } finally {
339             monitor.done();
340         }
341         return status;
342     }
343
344     /**
345      * {@inheritDoc}
346      */

347     protected RefactoringStatus aboutToPerformRefactoring(final Refactoring refactoring, final RefactoringDescriptor descriptor, final IProgressMonitor monitor) {
348         final RefactoringStatus status= new RefactoringStatus();
349         try {
350             monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 100);
351             status.merge(createNecessarySourceCode(refactoring, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
352             if (!status.hasFatalError()) {
353                 if (fCurrentRefactoring != null && fCurrentArguments != null)
354                     status.merge(fCurrentRefactoring.initialize(fCurrentArguments));
355             }
356         } finally {
357             monitor.done();
358         }
359         return status;
360     }
361
362     /**
363      * Can this wizard use the source attachment of the package fragment root if
364      * necessary?
365      *
366      * @return <code>true</code> to use the source attachment,
367      * <code>false</code> otherwise
368      */

369     protected boolean canUseSourceAttachment() {
370         final IPackageFragmentRoot root= getPackageFragmentRoot();
371         if (root != null) {
372             try {
373                 return root.getSourceAttachmentPath() != null;
374             } catch (JavaModelException exception) {
375                 JavaPlugin.log(exception);
376             }
377         }
378         return false;
379     }
380
381     /**
382      * Checks whether there are any refactorings to be executed which need a
383      * source attachment, but none exists.
384      *
385      * @param monitor
386      * the progress monitor
387      * @return a status describing the outcome of the check
388      */

389     protected RefactoringStatus checkSourceAttachmentRefactorings(final IProgressMonitor monitor) {
390         final RefactoringStatus status= new RefactoringStatus();
391         try {
392             if (!canUseSourceAttachment()) {
393                 final RefactoringDescriptorProxy[] proxies= getRefactoringHistory().getDescriptors();
394                 monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, proxies.length * 100);
395                 for (int index= 0; index < proxies.length; index++) {
396                     final RefactoringDescriptor descriptor= proxies[index].requestDescriptor(new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
397                     if (descriptor != null) {
398                         final int flags= descriptor.getFlags();
399                         if ((flags & JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT) != 0)
400                             status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(JarImportMessages.BinaryRefactoringHistoryWizard_error_missing_source_attachment, descriptor.getDescription())));
401                     }
402                 }
403             } else
404                 monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 1);
405         } finally {
406             monitor.done();
407         }
408         return status;
409     }
410
411     /**
412      * Creates the necessary source code for the refactoring.
413      *
414      * @param refactoring
415      * the refactoring to create the source code for
416      * @param monitor
417      * the progress monitor to use
418      */

419     private RefactoringStatus createNecessarySourceCode(final Refactoring refactoring, final IProgressMonitor monitor) {
420         final RefactoringStatus status= new RefactoringStatus();
421         try {
422             monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 240);
423             final IPackageFragmentRoot root= getPackageFragmentRoot();
424             if (root != null && fSourceFolder != null && fJavaProject != null) {
425                 try {
426                     final SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 40, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
427                     final IJavaElement[] elements= root.getChildren();
428                     final List JavaDoc list= new ArrayList JavaDoc(elements.length);
429                     try {
430                         subMonitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, elements.length);
431                         for (int index= 0; index < elements.length; index++) {
432                             final IJavaElement element= elements[index];
433                             if (!fProcessedFragments.contains(element) && !element.getElementName().equals(META_INF_FRAGMENT))
434                                 list.add(element);
435                             subMonitor.worked(1);
436                         }
437                     } finally {
438                         subMonitor.done();
439                     }
440                     if (!list.isEmpty()) {
441                         fProcessedFragments.addAll(list);
442                         final URI JavaDoc uri= fSourceFolder.getRawLocationURI();
443                         if (uri != null) {
444                             final IPackageFragmentRoot sourceFolder= fJavaProject.getPackageFragmentRoot(fSourceFolder);
445                             IWorkspaceRunnable runnable= null;
446                             if (canUseSourceAttachment()) {
447                                 runnable= new SourceCreationOperation(uri, list) {
448
449                                     private IPackageFragment fFragment= null;
450
451                                     protected final void createCompilationUnit(final IFileStore store, final String JavaDoc name, final String JavaDoc content, final IProgressMonitor pm) throws CoreException {
452                                         fFragment.createCompilationUnit(name, content, true, pm);
453                                     }
454
455                                     protected final void createPackageFragment(final IFileStore store, final String JavaDoc name, final IProgressMonitor pm) throws CoreException {
456                                         fFragment= sourceFolder.createPackageFragment(name, true, pm);
457                                     }
458                                 };
459                             } else {
460                                 runnable= new StubCreationOperation(uri, list, true) {
461
462                                     private IPackageFragment fFragment= null;
463
464                                     protected final void createCompilationUnit(final IFileStore store, final String JavaDoc name, final String JavaDoc content, final IProgressMonitor pm) throws CoreException {
465                                         fFragment.createCompilationUnit(name, content, true, pm);
466                                     }
467
468                                     protected final void createPackageFragment(final IFileStore store, final String JavaDoc name, final IProgressMonitor pm) throws CoreException {
469                                         fFragment= sourceFolder.createPackageFragment(name, true, pm);
470                                     }
471                                 };
472                             }
473                             try {
474                                 runnable.run(new SubProgressMonitor(monitor, 150, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
475                             } finally {
476                                 fSourceFolder.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 50, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
477                             }
478                         }
479                     }
480                 } catch (CoreException exception) {
481                     status.addFatalError(exception.getLocalizedMessage());
482                 }
483             }
484         } finally {
485             monitor.done();
486         }
487         return status;
488     }
489
490     /**
491      * {@inheritDoc}
492      */

493     protected Refactoring createRefactoring(final RefactoringDescriptor descriptor, final RefactoringStatus status) throws CoreException {
494         Assert.isNotNull(descriptor);
495         Refactoring refactoring= null;
496         if (descriptor instanceof JDTRefactoringDescriptor) {
497             final JDTRefactoringDescriptor javaDescriptor= (JDTRefactoringDescriptor) descriptor;
498             final RefactoringContribution contribution= RefactoringCore.getRefactoringContribution(javaDescriptor.getID());
499             if (contribution instanceof JDTRefactoringContribution) {
500                 final JDTRefactoringContribution extended= (JDTRefactoringContribution) contribution;
501                 refactoring= extended.createRefactoring(descriptor);
502             }
503             if (refactoring != null) {
504                 final RefactoringArguments arguments= javaDescriptor.createArguments();
505                 if (arguments instanceof JavaRefactoringArguments) {
506                     final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
507                     if (fJavaProject != null) {
508                         final String JavaDoc name= fJavaProject.getElementName();
509                         extended.setProject(name);
510                         String JavaDoc handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
511                         if (handle != null && !"".equals(handle)) //$NON-NLS-1$
512
extended.setAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, getTransformedHandle(name, handle));
513                         int count= 1;
514                         String JavaDoc attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
515                         while ((handle= extended.getAttribute(attribute)) != null) {
516                             if (!"".equals(handle)) //$NON-NLS-1$
517
extended.setAttribute(attribute, getTransformedHandle(name, handle));
518                             count++;
519                             attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
520                         }
521                     }
522                 } else
523                     status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments));
524                 if (refactoring instanceof IScriptableRefactoring) {
525                     fCurrentRefactoring= (IScriptableRefactoring) refactoring;
526                     fCurrentArguments= arguments;
527                 } else
528                     status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_initialization_error, javaDescriptor.getID())));
529             }
530             return refactoring;
531         }
532         return null;
533     }
534
535     /**
536      * Deconfigures the classpath after all refactoring have been performed.
537      *
538      * @param entries
539      * the classpath entries to reset the project to
540      * @param monitor
541      * the progress monitor to use
542      * @return <code>true</code> if the classpath has been changed,
543      * <code>false</code> otherwise
544      * @throws CoreException
545      * if an error occurs while deconfiguring the classpath
546      */

547     protected boolean deconfigureClasspath(IClasspathEntry[] entries, IProgressMonitor monitor) throws CoreException {
548         return false;
549     }
550
551     /**
552      * Deconfigures the classpath of the project after refactoring.
553      *
554      * @param monitor
555      * the progress monitor to use
556      * @throws CoreException
557      * if an error occurs while deconfiguring the classpath
558      */

559     private void deconfigureClasspath(final IProgressMonitor monitor) throws CoreException {
560         try {
561             monitor.beginTask(JarImportMessages.JarImportWizard_cleanup_import, 300);
562             if (fJavaProject != null) {
563                 final IClasspathEntry[] entries= fJavaProject.readRawClasspath();
564                 final boolean changed= deconfigureClasspath(entries, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
565                 final RefactoringHistory history= getRefactoringHistory();
566                 final boolean valid= history != null && !history.isEmpty();
567                 if (valid)
568                     RefactoringCore.getUndoManager().flush();
569                 if (valid || changed)
570                     fJavaProject.setRawClasspath(entries, changed, new SubProgressMonitor(monitor, 60, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
571             }
572             if (fSourceFolder != null) {
573                 final IFileStore store= EFS.getStore(fSourceFolder.getRawLocationURI());
574                 if (store.fetchInfo(EFS.NONE, new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).exists())
575                     store.delete(EFS.NONE, new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
576                 fSourceFolder.delete(true, false, new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
577                 fSourceFolder.clearHistory(new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
578                 fSourceFolder= null;
579             }
580             if (fJavaProject != null) {
581                 try {
582                     fJavaProject.getResource().refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
583                 } catch (CoreException exception) {
584                     JavaPlugin.log(exception);
585                 }
586             }
587         } finally {
588             fJavaProject= null;
589             monitor.done();
590         }
591     }
592
593     /**
594      * Returns the package fragment root to stub.
595      *
596      * @return the package fragment root to stub, or <code>null</code>
597      */

598     protected abstract IPackageFragmentRoot getPackageFragmentRoot();
599
600     /**
601      * Returns the refactoring history to perform.
602      *
603      * @return the refactoring history to perform, or the empty history
604      */

605     protected abstract RefactoringHistory getRefactoringHistory();
606
607     /**
608      * Returns the transformed handle corresponding to the specified input
609      * handle.
610      *
611      * @param project
612      * the project, or <code>null</code> for the workspace
613      * @param handle
614      * the handle to transform
615      * @return the transformed handle, or the original one if nothing needed to
616      * be transformed
617      */

618     private String JavaDoc getTransformedHandle(final String JavaDoc project, final String JavaDoc handle) {
619         if (fSourceFolder != null) {
620             final IJavaElement target= JavaCore.create(fSourceFolder);
621             if (target instanceof IPackageFragmentRoot) {
622                 final IPackageFragmentRoot extended= (IPackageFragmentRoot) target;
623                 String JavaDoc sourceIdentifier= null;
624                 final IJavaElement element= JDTRefactoringDescriptor.handleToElement(project, handle, false);
625                 if (element != null) {
626                     final IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
627                     if (root != null)
628                         sourceIdentifier= root.getHandleIdentifier();
629                     else {
630                         final IJavaProject javaProject= element.getJavaProject();
631                         if (javaProject != null)
632                             sourceIdentifier= javaProject.getHandleIdentifier();
633                     }
634                     if (sourceIdentifier != null) {
635                         final IJavaElement result= JavaCore.create(extended.getHandleIdentifier() + element.getHandleIdentifier().substring(sourceIdentifier.length()));
636                         if (result != null)
637                             return JDTRefactoringDescriptor.elementToHandle(project, result);
638                     }
639                 }
640             }
641         }
642         return handle;
643     }
644
645     /**
646      * {@inheritDoc}
647      */

648     protected RefactoringStatus historyPerformed(final IProgressMonitor monitor) {
649         try {
650             monitor.beginTask(JarImportMessages.JarImportWizard_cleanup_import, 100);
651             final RefactoringStatus status= super.historyPerformed(new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
652             if (!status.hasFatalError()) {
653                 try {
654                     deconfigureClasspath(new SubProgressMonitor(monitor, 90, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
655                 } catch (CoreException exception) {
656                     status.addError(exception.getLocalizedMessage());
657                 } finally {
658                     try {
659                         CoreUtility.enableAutoBuild(fAutoBuild);
660                     } catch (CoreException exception) {
661                         JavaPlugin.log(exception);
662                     }
663                 }
664             }
665             return status;
666         } finally {
667             monitor.done();
668         }
669     }
670
671     /**
672      * {@inheritDoc}
673      */

674     public boolean performCancel() {
675         fCancelled= true;
676         return super.performCancel();
677     }
678
679     /**
680      * {@inheritDoc}
681      */

682     protected RefactoringStatus refactoringPerformed(final Refactoring refactoring, final IProgressMonitor monitor) {
683         try {
684             monitor.beginTask("", 120); //$NON-NLS-1$
685
final RefactoringStatus status= super.refactoringPerformed(refactoring, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
686             if (!status.hasFatalError()) {
687                 if (fSourceFolder != null) {
688                     try {
689                         fSourceFolder.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
690                     } catch (CoreException exception) {
691                         JavaPlugin.log(exception);
692                     }
693                 }
694             }
695             return status;
696         } finally {
697             monitor.done();
698         }
699     }
700
701     /**
702      * {@inheritDoc}
703      */

704     protected boolean selectPreviewChange(final Change change) {
705         if (fSourceFolder != null) {
706             final IPath source= fSourceFolder.getFullPath();
707             final Object JavaDoc element= change.getModifiedElement();
708             if (element instanceof IAdaptable) {
709                 final IAdaptable adaptable= (IAdaptable) element;
710                 final IResource resource= (IResource) adaptable.getAdapter(IResource.class);
711                 if (resource != null && source.isPrefixOf(resource.getFullPath()))
712                     return false;
713             }
714         }
715         return super.selectPreviewChange(change);
716     }
717
718     /**
719      * {@inheritDoc}
720      */

721     protected boolean selectStatusEntry(final RefactoringStatusEntry entry) {
722         if (fSourceFolder != null) {
723             final IPath source= fSourceFolder.getFullPath();
724             final RefactoringStatusContext context= entry.getContext();
725             if (context instanceof JavaStatusContext) {
726                 final JavaStatusContext extended= (JavaStatusContext) context;
727                 final ICompilationUnit unit= extended.getCompilationUnit();
728                 if (unit != null) {
729                     final IResource resource= unit.getResource();
730                     if (resource != null && source.isPrefixOf(resource.getFullPath()))
731                         return false;
732                 }
733             }
734         }
735         return super.selectStatusEntry(entry);
736     }
737 }
738
Popular Tags