KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > wizards > JavaProjectWizardSecondPage


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.jdt.internal.ui.wizards;
12
13 import java.io.File JavaDoc;
14 import java.io.FileInputStream JavaDoc;
15 import java.io.FileOutputStream JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.io.InputStream JavaDoc;
18 import java.io.OutputStream JavaDoc;
19 import java.lang.reflect.InvocationTargetException JavaDoc;
20 import java.net.URI JavaDoc;
21 import java.net.URISyntaxException JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Arrays JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.Map JavaDoc;
26
27 import org.eclipse.core.filesystem.EFS;
28 import org.eclipse.core.filesystem.IFileStore;
29 import org.eclipse.core.filesystem.URIUtil;
30
31 import org.eclipse.core.runtime.Assert;
32 import org.eclipse.core.runtime.CoreException;
33 import org.eclipse.core.runtime.IPath;
34 import org.eclipse.core.runtime.IProgressMonitor;
35 import org.eclipse.core.runtime.IStatus;
36 import org.eclipse.core.runtime.NullProgressMonitor;
37 import org.eclipse.core.runtime.OperationCanceledException;
38 import org.eclipse.core.runtime.Path;
39 import org.eclipse.core.runtime.Status;
40 import org.eclipse.core.runtime.SubProgressMonitor;
41
42 import org.eclipse.core.resources.IFolder;
43 import org.eclipse.core.resources.IProject;
44 import org.eclipse.core.resources.IResource;
45 import org.eclipse.core.resources.IResourceStatus;
46 import org.eclipse.core.resources.ResourcesPlugin;
47
48 import org.eclipse.jface.dialogs.ErrorDialog;
49 import org.eclipse.jface.operation.IRunnableWithProgress;
50 import org.eclipse.jface.preference.IPreferenceStore;
51
52 import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
53
54 import org.eclipse.jdt.core.IClasspathEntry;
55 import org.eclipse.jdt.core.IJavaProject;
56 import org.eclipse.jdt.core.JavaCore;
57
58 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
59 import org.eclipse.jdt.internal.corext.util.Messages;
60
61 import org.eclipse.jdt.launching.JavaRuntime;
62
63 import org.eclipse.jdt.ui.JavaUI;
64 import org.eclipse.jdt.ui.PreferenceConstants;
65 import org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage;
66
67 import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
68 import org.eclipse.jdt.internal.ui.util.CoreUtility;
69 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
70
71 /**
72  * As addition to the JavaCapabilityConfigurationPage, the wizard does an
73  * early project creation (so that linked folders can be defined) and, if an
74  * existing external location was specified, offers to do a classpath detection
75  */

76 public class JavaProjectWizardSecondPage extends JavaCapabilityConfigurationPage {
77
78     private static final String JavaDoc FILENAME_PROJECT= ".project"; //$NON-NLS-1$
79
private static final String JavaDoc FILENAME_CLASSPATH= ".classpath"; //$NON-NLS-1$
80

81     private final JavaProjectWizardFirstPage fFirstPage;
82
83     private URI JavaDoc fCurrProjectLocation; // null if location is platform location
84
private IProject fCurrProject;
85     
86     private boolean fKeepContent;
87
88     private File JavaDoc fDotProjectBackup;
89     private File JavaDoc fDotClasspathBackup;
90     private Boolean JavaDoc fIsAutobuild;
91
92     /**
93      * Constructor for JavaProjectWizardSecondPage.
94      * @param mainPage the first page of the wizard
95      */

96     public JavaProjectWizardSecondPage(JavaProjectWizardFirstPage mainPage) {
97         fFirstPage= mainPage;
98         fCurrProjectLocation= null;
99         fCurrProject= null;
100         fKeepContent= false;
101         
102         fDotProjectBackup= null;
103         fDotClasspathBackup= null;
104         fIsAutobuild= null;
105     }
106     
107     protected boolean useNewSourcePage() {
108         return true;
109     }
110     
111     
112     /* (non-Javadoc)
113      * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
114      */

115     public void setVisible(boolean visible) {
116         if (visible) {
117             IStatus status= changeToNewProject();
118             if (status != null && !status.isOK()) {
119                 ErrorDialog.openError(getShell(), NewWizardMessages.JavaProjectWizardSecondPage_error_title, null, status);
120             }
121         } else {
122             removeProject();
123         }
124         super.setVisible(visible);
125         if (visible) {
126
127             setFocus();
128         }
129     }
130
131     private IStatus changeToNewProject() {
132         fKeepContent= fFirstPage.getDetect();
133
134         class UpdateRunnable implements IRunnableWithProgress {
135             public IStatus infoStatus= Status.OK_STATUS;
136             
137             public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
138                 try {
139                     if (fIsAutobuild == null) {
140                         fIsAutobuild= Boolean.valueOf(CoreUtility.enableAutoBuild(false));
141                     }
142                     infoStatus= updateProject(monitor);
143                 } catch (CoreException e) {
144                     throw new InvocationTargetException JavaDoc(e);
145                 } catch (OperationCanceledException e) {
146                     throw new InterruptedException JavaDoc();
147                 } finally {
148                     monitor.done();
149                 }
150             }
151         }
152         UpdateRunnable op= new UpdateRunnable();
153         try {
154             getContainer().run(true, false, new WorkspaceModifyDelegatingOperation(op));
155             return op.infoStatus;
156         } catch (InvocationTargetException JavaDoc e) {
157             final String JavaDoc title= NewWizardMessages.JavaProjectWizardSecondPage_error_title;
158             final String JavaDoc message= NewWizardMessages.JavaProjectWizardSecondPage_error_message;
159             ExceptionHandler.handle(e, getShell(), title, message);
160         } catch (InterruptedException JavaDoc e) {
161             // cancel pressed
162
}
163         return null;
164     }
165     
166     final IStatus updateProject(IProgressMonitor monitor) throws CoreException, InterruptedException JavaDoc {
167         
168         IStatus result= StatusInfo.OK_STATUS;
169         
170         fCurrProject= fFirstPage.getProjectHandle();
171         fCurrProjectLocation= getProjectLocationURI();
172         
173         if (monitor == null) {
174             monitor= new NullProgressMonitor();
175         }
176         try {
177             monitor.beginTask(NewWizardMessages.JavaProjectWizardSecondPage_operation_initialize, 7);
178             if (monitor.isCanceled()) {
179                 throw new OperationCanceledException();
180             }
181             
182             URI JavaDoc realLocation= fCurrProjectLocation;
183             if (fCurrProjectLocation == null) { // inside workspace
184
try {
185                     URI JavaDoc rootLocation= ResourcesPlugin.getWorkspace().getRoot().getLocationURI();
186                     realLocation= new URI JavaDoc(rootLocation.getScheme(), null,
187                         Path.fromPortableString(rootLocation.getPath()).append(fCurrProject.getName()).toString(),
188                         null);
189                 } catch (URISyntaxException JavaDoc e) {
190                     Assert.isTrue(false, "Can't happen"); //$NON-NLS-1$
191
}
192             }
193
194             rememberExistingFiles(realLocation);
195             
196             try {
197                 createProject(fCurrProject, fCurrProjectLocation, new SubProgressMonitor(monitor, 2));
198             } catch (CoreException e) {
199                 if (e.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) {
200                     result= new StatusInfo(IStatus.INFO, Messages.format(NewWizardMessages.JavaProjectWizardSecondPage_DeleteCorruptProjectFile_message, e.getLocalizedMessage()));
201                     
202                     deleteProjectFile(realLocation);
203                     if (fCurrProject.exists())
204                         fCurrProject.delete(true, null);
205                     
206                     createProject(fCurrProject, fCurrProjectLocation, null);
207                 } else {
208                     throw e;
209                 }
210             }
211                 
212             IClasspathEntry[] entries= null;
213             IPath outputLocation= null;
214     
215             if (fFirstPage.getDetect()) {
216                 if (!fCurrProject.getFile(FILENAME_CLASSPATH).exists()) {
217                     final ClassPathDetector detector= new ClassPathDetector(fCurrProject, new SubProgressMonitor(monitor, 2));
218                     entries= detector.getClasspath();
219                     outputLocation= detector.getOutputLocation();
220                 } else {
221                     monitor.worked(2);
222                 }
223             } else if (fFirstPage.isSrcBin()) {
224                 IPreferenceStore store= PreferenceConstants.getPreferenceStore();
225                 IPath srcPath= new Path(store.getString(PreferenceConstants.SRCBIN_SRCNAME));
226                 IPath binPath= new Path(store.getString(PreferenceConstants.SRCBIN_BINNAME));
227                 
228                 if (srcPath.segmentCount() > 0) {
229                     IFolder folder= fCurrProject.getFolder(srcPath);
230                     CoreUtility.createFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
231                 } else {
232                     monitor.worked(1);
233                 }
234                 
235                 if (binPath.segmentCount() > 0 && !binPath.equals(srcPath)) {
236                     IFolder folder= fCurrProject.getFolder(binPath);
237                     CoreUtility.createDerivedFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
238                 } else {
239                     monitor.worked(1);
240                 }
241                 
242                 final IPath projectPath= fCurrProject.getFullPath();
243
244                 // configure the classpath entries, including the default jre library.
245
List JavaDoc cpEntries= new ArrayList JavaDoc();
246                 cpEntries.add(JavaCore.newSourceEntry(projectPath.append(srcPath)));
247                 cpEntries.addAll(Arrays.asList(getDefaultClasspathEntry()));
248                 entries= (IClasspathEntry[]) cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
249                 
250                 // configure the output location
251
outputLocation= projectPath.append(binPath);
252             } else {
253                 IPath projectPath= fCurrProject.getFullPath();
254                 List JavaDoc cpEntries= new ArrayList JavaDoc();
255                 cpEntries.add(JavaCore.newSourceEntry(projectPath));
256                 cpEntries.addAll(Arrays.asList(getDefaultClasspathEntry()));
257                 entries= (IClasspathEntry[]) cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
258
259                 outputLocation= projectPath;
260                 monitor.worked(2);
261             }
262             if (monitor.isCanceled()) {
263                 throw new OperationCanceledException();
264             }
265             
266             init(JavaCore.create(fCurrProject), outputLocation, entries, false);
267             configureJavaProject(new SubProgressMonitor(monitor, 3)); // create the Java project to allow the use of the new source folder page
268
} finally {
269             monitor.done();
270         }
271         return result;
272     }
273     
274     private URI JavaDoc getProjectLocationURI() throws CoreException {
275         if (fFirstPage.isInWorkspace()) {
276             return null;
277         }
278         return URIUtil.toURI(fFirstPage.getLocationPath());
279     }
280     
281     private IClasspathEntry[] getDefaultClasspathEntry() {
282         IClasspathEntry[] defaultJRELibrary= PreferenceConstants.getDefaultJRELibrary();
283         String JavaDoc compliance= fFirstPage.getCompilerCompliance();
284         IPath jreContainerPath= new Path(JavaRuntime.JRE_CONTAINER);
285         if (compliance == null || defaultJRELibrary.length > 1 || !jreContainerPath.isPrefixOf(defaultJRELibrary[0].getPath())) {
286             // use default
287
return defaultJRELibrary;
288         }
289         IPath newPath= fFirstPage.getJREContainerPath();
290         if (newPath != null) {
291             return new IClasspathEntry[] { JavaCore.newContainerEntry(newPath) };
292         }
293         return defaultJRELibrary;
294     }
295     
296     private void deleteProjectFile(URI JavaDoc projectLocation) throws CoreException {
297         IFileStore file= EFS.getStore(projectLocation);
298         if (file.fetchInfo().exists()) {
299             IFileStore projectFile= file.getChild(FILENAME_PROJECT);
300             if (projectFile.fetchInfo().exists()) {
301                 projectFile.delete(EFS.NONE, null);
302             }
303         }
304     }
305     
306     private void rememberExistingFiles(URI JavaDoc projectLocation) throws CoreException {
307         fDotProjectBackup= null;
308         fDotClasspathBackup= null;
309         
310         IFileStore file= EFS.getStore(projectLocation);
311         if (file.fetchInfo().exists()) {
312             IFileStore projectFile= file.getChild(FILENAME_PROJECT);
313             if (projectFile.fetchInfo().exists()) {
314                 fDotProjectBackup= createBackup(projectFile, "project-desc"); //$NON-NLS-1$
315
}
316             IFileStore classpathFile= file.getChild(FILENAME_CLASSPATH);
317             if (classpathFile.fetchInfo().exists()) {
318                 fDotClasspathBackup= createBackup(classpathFile, "classpath-desc"); //$NON-NLS-1$
319
}
320         }
321     }
322     
323     private void restoreExistingFiles(URI JavaDoc projectLocation, IProgressMonitor monitor) throws CoreException {
324         int ticks= ((fDotProjectBackup != null ? 1 : 0) + (fDotClasspathBackup != null ? 1 : 0)) * 2;
325         monitor.beginTask("", ticks); //$NON-NLS-1$
326
try {
327             IFileStore projectFile= EFS.getStore(projectLocation).getChild(FILENAME_PROJECT);
328             projectFile.delete(EFS.NONE, new SubProgressMonitor(monitor, 1));
329             if (fDotProjectBackup != null) {
330                 copyFile(fDotProjectBackup, projectFile, new SubProgressMonitor(monitor, 1));
331             }
332         } catch (IOException JavaDoc e) {
333             IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, NewWizardMessages.JavaProjectWizardSecondPage_problem_restore_project, e);
334             throw new CoreException(status);
335         }
336         try {
337             IFileStore classpathFile= EFS.getStore(projectLocation).getChild(FILENAME_CLASSPATH);
338             classpathFile.delete(EFS.NONE, new SubProgressMonitor(monitor, 1));
339             if (fDotClasspathBackup != null) {
340                 copyFile(fDotClasspathBackup, classpathFile, new SubProgressMonitor(monitor, 1));
341             }
342         } catch (IOException JavaDoc e) {
343             IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, NewWizardMessages.JavaProjectWizardSecondPage_problem_restore_classpath, e);
344             throw new CoreException(status);
345         }
346     }
347     
348     private File JavaDoc createBackup(IFileStore source, String JavaDoc name) throws CoreException {
349         try {
350             File JavaDoc bak= File.createTempFile("eclipse-" + name, ".bak"); //$NON-NLS-1$//$NON-NLS-2$
351
copyFile(source, bak);
352             return bak;
353         } catch (IOException JavaDoc e) {
354             IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, Messages.format(NewWizardMessages.JavaProjectWizardSecondPage_problem_backup, name), e);
355             throw new CoreException(status);
356         }
357     }
358     
359     private void copyFile(IFileStore source, File JavaDoc target) throws IOException JavaDoc, CoreException {
360         InputStream JavaDoc is= source.openInputStream(EFS.NONE, null);
361         FileOutputStream JavaDoc os= new FileOutputStream JavaDoc(target);
362         copyFile(is, os);
363     }
364     
365     private void copyFile(File JavaDoc source, IFileStore target, IProgressMonitor monitor) throws IOException JavaDoc, CoreException {
366         FileInputStream JavaDoc is= new FileInputStream JavaDoc(source);
367         OutputStream JavaDoc os= target.openOutputStream(EFS.NONE, monitor);
368         copyFile(is, os);
369     }
370     
371     private void copyFile(InputStream JavaDoc is, OutputStream JavaDoc os) throws IOException JavaDoc {
372         try {
373             byte[] buffer = new byte[8192];
374             while (true) {
375                 int bytesRead= is.read(buffer);
376                 if (bytesRead == -1)
377                     break;
378                 
379                 os.write(buffer, 0, bytesRead);
380             }
381         } finally {
382             try {
383                 is.close();
384             } finally {
385                 os.close();
386             }
387         }
388     }
389     
390     /**
391      * Called from the wizard on finish.
392      * @param monitor the progress monitor
393      * @throws CoreException thrown when the project creation or configuration failed
394      * @throws InterruptedException thrown when the user cancelled the project creation
395      */

396     public void performFinish(IProgressMonitor monitor) throws CoreException, InterruptedException JavaDoc {
397         try {
398             monitor.beginTask(NewWizardMessages.JavaProjectWizardSecondPage_operation_create, 3);
399             if (fCurrProject == null) {
400                 updateProject(new SubProgressMonitor(monitor, 1));
401             }
402             configureJavaProject(new SubProgressMonitor(monitor, 2));
403             
404             if (!fKeepContent) {
405                 String JavaDoc compliance= fFirstPage.getCompilerCompliance();
406                 if (compliance != null) {
407                     IJavaProject project= JavaCore.create(fCurrProject);
408                     Map JavaDoc options= project.getOptions(false);
409                     JavaModelUtil.setCompilanceOptions(options, compliance);
410                     JavaModelUtil.setDefaultClassfileOptions(options, compliance); // complete compliance options
411
project.setOptions(options);
412                 }
413             }
414         } finally {
415             monitor.done();
416             fCurrProject= null;
417             if (fIsAutobuild != null) {
418                 CoreUtility.enableAutoBuild(fIsAutobuild.booleanValue());
419                 fIsAutobuild= null;
420             }
421         }
422     }
423
424     private void removeProject() {
425         if (fCurrProject == null || !fCurrProject.exists()) {
426             return;
427         }
428         
429         IRunnableWithProgress op= new IRunnableWithProgress() {
430             public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
431                 doRemoveProject(monitor);
432             }
433         };
434     
435         try {
436             getContainer().run(true, true, new WorkspaceModifyDelegatingOperation(op));
437         } catch (InvocationTargetException JavaDoc e) {
438             final String JavaDoc title= NewWizardMessages.JavaProjectWizardSecondPage_error_remove_title;
439             final String JavaDoc message= NewWizardMessages.JavaProjectWizardSecondPage_error_remove_message;
440             ExceptionHandler.handle(e, getShell(), title, message);
441         } catch (InterruptedException JavaDoc e) {
442             // cancel pressed
443
}
444     }
445     
446     final void doRemoveProject(IProgressMonitor monitor) throws InvocationTargetException JavaDoc {
447         final boolean noProgressMonitor= (fCurrProjectLocation == null); // inside workspace
448
if (monitor == null || noProgressMonitor) {
449             monitor= new NullProgressMonitor();
450         }
451         monitor.beginTask(NewWizardMessages.JavaProjectWizardSecondPage_operation_remove, 3);
452         try {
453             try {
454                 URI JavaDoc projLoc= fCurrProject.getLocationURI();
455                 
456                 boolean removeContent= !fKeepContent && fCurrProject.isSynchronized(IResource.DEPTH_INFINITE);
457                 fCurrProject.delete(removeContent, false, new SubProgressMonitor(monitor, 2));
458                 
459                 restoreExistingFiles(projLoc, new SubProgressMonitor(monitor, 1));
460             } finally {
461                 CoreUtility.enableAutoBuild(fIsAutobuild.booleanValue()); // fIsAutobuild must be set
462
fIsAutobuild= null;
463             }
464         } catch (CoreException e) {
465             throw new InvocationTargetException JavaDoc(e);
466         } finally {
467             monitor.done();
468             fCurrProject= null;
469             fKeepContent= false;
470         }
471     }
472
473     /**
474      * Called from the wizard on cancel.
475      */

476     public void performCancel() {
477         removeProject();
478     }
479  }
480
Popular Tags