KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > launcher > LauncherUtils


1 /*******************************************************************************
2  * Copyright (c) 2003, 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.launcher;
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.lang.reflect.InvocationTargetException JavaDoc;
18 import java.util.ArrayList JavaDoc;
19 import java.util.HashSet JavaDoc;
20 import java.util.Iterator JavaDoc;
21 import java.util.Properties JavaDoc;
22 import java.util.Set JavaDoc;
23 import java.util.Stack JavaDoc;
24 import java.util.StringTokenizer JavaDoc;
25
26 import org.eclipse.core.resources.IProject;
27 import org.eclipse.core.resources.IResource;
28 import org.eclipse.core.resources.ResourcesPlugin;
29 import org.eclipse.core.runtime.CoreException;
30 import org.eclipse.core.runtime.IPath;
31 import org.eclipse.core.runtime.IProgressMonitor;
32 import org.eclipse.core.runtime.IStatus;
33 import org.eclipse.core.runtime.Path;
34 import org.eclipse.core.runtime.Status;
35 import org.eclipse.debug.core.ILaunchConfiguration;
36 import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
37 import org.eclipse.jdt.core.IClasspathEntry;
38 import org.eclipse.jdt.core.IJavaProject;
39 import org.eclipse.jdt.core.JavaCore;
40 import org.eclipse.jdt.core.JavaModelException;
41 import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
42 import org.eclipse.jface.dialogs.DialogSettings;
43 import org.eclipse.jface.dialogs.IDialogConstants;
44 import org.eclipse.jface.dialogs.IDialogSettings;
45 import org.eclipse.jface.dialogs.MessageDialog;
46 import org.eclipse.jface.preference.IPreferenceStore;
47 import org.eclipse.osgi.util.NLS;
48 import org.eclipse.pde.core.plugin.IPluginModelBase;
49 import org.eclipse.pde.core.plugin.PluginRegistry;
50 import org.eclipse.pde.internal.core.DependencyManager;
51 import org.eclipse.pde.internal.core.PDECore;
52 import org.eclipse.pde.internal.core.WorkspaceModelManager;
53 import org.eclipse.pde.internal.core.util.CoreUtility;
54 import org.eclipse.pde.internal.ui.IPDEUIConstants;
55 import org.eclipse.pde.internal.ui.IPreferenceConstants;
56 import org.eclipse.pde.internal.ui.PDEPlugin;
57 import org.eclipse.pde.internal.ui.PDEUIMessages;
58 import org.eclipse.pde.internal.ui.wizards.tools.IOrganizeManifestsSettings;
59 import org.eclipse.pde.internal.ui.wizards.tools.OrganizeManifestsOperation;
60 import org.eclipse.pde.ui.launcher.IPDELauncherConstants;
61 import org.eclipse.swt.widgets.Display;
62 import org.eclipse.swt.widgets.Shell;
63 import org.eclipse.ui.IWorkbenchWindow;
64
65 public class LauncherUtils {
66
67     private static final String JavaDoc TIMESTAMP = "timestamp"; //$NON-NLS-1$
68
private static final String JavaDoc FILE_NAME = "dep-timestamp.properties"; //$NON-NLS-1$
69
private static Properties JavaDoc fLastRun;
70
71     public static Display getDisplay() {
72         Display display = Display.getCurrent();
73         if (display == null) {
74             display = Display.getDefault();
75         }
76         return display;
77     }
78
79     public final static Shell getActiveShell() {
80         IWorkbenchWindow window =
81             PDEPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
82         if (window == null) {
83             IWorkbenchWindow[] windows = PDEPlugin.getDefault().getWorkbench().getWorkbenchWindows();
84             if (windows.length > 0)
85                 return windows[0].getShell();
86         } else
87             return window.getShell();
88         return getDisplay().getActiveShell();
89     }
90
91     public static boolean clearWorkspace(ILaunchConfiguration configuration,
92             String JavaDoc workspace, IProgressMonitor monitor) throws CoreException {
93         // If the workspace is not defined, there is no workspace to clear
94
// What will happen is that the workspace chooser dialog will be
95
// brought up because no -data parameter will be specified on the
96
// launch
97
if (workspace.length() == 0) {
98             monitor.done();
99             return true;
100         }
101
102         File JavaDoc workspaceFile = new Path(workspace).toFile().getAbsoluteFile();
103         if (configuration.getAttribute(IPDELauncherConstants.DOCLEAR, false)
104                 && workspaceFile.exists()) {
105             boolean doClear = !configuration.getAttribute(IPDELauncherConstants.ASKCLEAR,
106                     true);
107             if (!doClear) {
108                 int result = confirmDeleteWorkspace(workspaceFile);
109                 if (result == 2 || result == -1) {
110                     monitor.done();
111                     return false;
112                 }
113                 doClear = result == 0;
114             }
115
116             if (doClear) {
117                 if(configuration.getAttribute(IPDEUIConstants.DOCLEARLOG, false)) {
118                     LauncherUtils.clearWorkspaceLog(workspace);
119                 } else {
120                     CoreUtility.deleteContent(workspaceFile);
121                 }
122             }
123         }
124
125         monitor.done();
126         return true;
127     }
128
129     private static int confirmDeleteWorkspace(final File JavaDoc workspaceFile) {
130         String JavaDoc message = NLS.bind(
131                 PDEUIMessages.WorkbenchLauncherConfigurationDelegate_confirmDeleteWorkspace,
132                 workspaceFile.getPath());
133         return generateDialog(message);
134     }
135
136     public static boolean generateConfigIni() {
137         String JavaDoc message = PDEUIMessages.LauncherUtils_generateConfigIni;
138         return generateDialog(message) == 0;
139     }
140
141     private static int generateDialog(final String JavaDoc message) {
142         final int[] result = new int[1];
143         getDisplay().syncExec(new Runnable JavaDoc() {
144             public void run() {
145                 String JavaDoc title = PDEUIMessages.LauncherUtils_title;
146                 MessageDialog dialog = new MessageDialog(getActiveShell(),
147                         title, null, message, MessageDialog.QUESTION, new String JavaDoc[] {
148                     IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL,
149                     IDialogConstants.CANCEL_LABEL }, 0);
150                 result[0] = dialog.open();
151             }
152         });
153         return result[0];
154     }
155
156     public static void validateProjectDependencies(ILaunchConfiguration launch, final IProgressMonitor monitor) {
157         IPreferenceStore store = PDEPlugin.getDefault().getPreferenceStore();
158         if (!store.getBoolean(IPreferenceConstants.PROP_AUTO_MANAGE))
159             return;
160
161         String JavaDoc timeStamp, selected, deSelected;
162         boolean useDefault, autoAdd;
163         try {
164             timeStamp = launch.getAttribute(TIMESTAMP, "0"); //$NON-NLS-1$
165
selected = launch.getAttribute(IPDELauncherConstants.SELECTED_WORKSPACE_PLUGINS, ""); //$NON-NLS-1$
166
deSelected = launch.getAttribute(IPDELauncherConstants.DESELECTED_WORKSPACE_PLUGINS, ""); //$NON-NLS-1$
167
autoAdd = launch.getAttribute(IPDELauncherConstants.AUTOMATIC_ADD, true);
168             useDefault = launch.getAttribute(IPDELauncherConstants.USE_DEFAULT, true);
169             useDefault |= launch.getAttribute(IPDELauncherConstants.USEFEATURES, false);
170             final ArrayList JavaDoc projects = new ArrayList JavaDoc();
171             if (useDefault)
172                 handleUseDefault(timeStamp, projects);
173             else if (autoAdd)
174                 handleDeselectedPlugins(timeStamp, deSelected, projects);
175             else
176                 handleSelectedPlugins(timeStamp, selected, projects);
177
178             if (!projects.isEmpty())
179                 Display.getDefault().syncExec(new Runnable JavaDoc() {
180                     public void run() {
181                         OrganizeManifestsOperation op = new OrganizeManifestsOperation(projects);
182                         op.setOperations(getSettings());
183                         try {
184                             op.run(monitor);
185                             // update table for each project with current time stamp
186
Properties JavaDoc table = getLastRun();
187                             String JavaDoc ts = Long.toString(System.currentTimeMillis());
188                             Iterator JavaDoc it = projects.iterator();
189                             while (it.hasNext())
190                                 table.put(((IProject)it.next()).getName(), ts);
191                         } catch (InvocationTargetException JavaDoc e) {
192                         } catch (InterruptedException JavaDoc e) {
193                         }
194                     }
195                 });
196
197             ILaunchConfigurationWorkingCopy wc = null;
198             if (launch.isWorkingCopy())
199                 wc = (ILaunchConfigurationWorkingCopy)launch;
200             else
201                 wc = launch.getWorkingCopy();
202             wc.setAttribute(TIMESTAMP, Long.toString(System.currentTimeMillis()));
203             wc.doSave();
204         } catch (CoreException e) {
205         }
206     }
207
208     private static IDialogSettings getSettings() {
209         IDialogSettings settings = new DialogSettings(""); //$NON-NLS-1$
210
settings.put(IOrganizeManifestsSettings.PROP_ADD_MISSING, true);
211         settings.put(IOrganizeManifestsSettings.PROP_MARK_INTERNAL, true);
212         settings.put(IOrganizeManifestsSettings.PROP_REMOVE_UNRESOLVED_EX, true);
213         settings.put(IOrganizeManifestsSettings.PROP_MODIFY_DEP, true);
214         settings.put(IOrganizeManifestsSettings.PROP_RESOLVE_IMP_MARK_OPT, true);
215         settings.put(IOrganizeManifestsSettings.PROP_REMOVE_LAZY, true);
216         settings.put(IOrganizeManifestsSettings.PROP_ADD_DEPENDENCIES, true);
217         return settings;
218     }
219
220     private static String JavaDoc getTimeStamp(IProject project) {
221         IJavaProject jp = JavaCore.create(project);
222         try {
223             long timeStamp = 0;
224             IClasspathEntry[] entries = jp.getResolvedClasspath(true);
225             for (int i = 0; i < entries.length; i++) {
226                 if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
227                     File JavaDoc file;
228                     IPath location = entries[i].getOutputLocation();
229                     if (location == null)
230                         location = jp.getOutputLocation();
231                     IResource res = project.getWorkspace().getRoot().findMember(location);
232                     IPath path = res == null ? null : res.getLocation();
233                     if (path == null)
234                         continue;
235                     file = path.toFile();
236                     Stack JavaDoc files = new Stack JavaDoc();
237                     files.push(file);
238                     while(!files.isEmpty()) {
239                         file = (File JavaDoc) files.pop();
240                         if (file.isDirectory()) {
241                             File JavaDoc[] children = file.listFiles();
242                             for (int j =0 ; j < children.length; j++)
243                                 files.push(children[j]);
244                         } else
245                             if (file.getName().endsWith(".class") && timeStamp < file.lastModified()) //$NON-NLS-1$
246
timeStamp = file.lastModified();
247                     }
248                 }
249             }
250             String JavaDoc[] otherFiles = {"META-INF/MANIFEST.MF", "build.properties"}; //$NON-NLS-1$ //$NON-NLS-2$
251
for (int i = 0; i < otherFiles.length; i++) {
252                 IResource file = project.getFile(otherFiles[i]);
253                 if (file != null) {
254                     long fileTimeStamp = file.getRawLocation().toFile().lastModified();
255                     if (timeStamp < fileTimeStamp)
256                         timeStamp = fileTimeStamp;
257                 }
258             }
259             return Long.toString(timeStamp);
260         } catch (JavaModelException e) {
261         }
262         return "0"; //$NON-NLS-1$
263
}
264
265     private static void handleUseDefault(String JavaDoc launcherTimeStamp, ArrayList JavaDoc projects) {
266         IProject[] projs = ResourcesPlugin.getWorkspace().getRoot().getProjects();
267         for (int i = 0; i < projs.length; i++) {
268             if (!WorkspaceModelManager.isPluginProject(projs[i]))
269                 continue;
270             String JavaDoc timestamp = getTimeStamp(projs[i]);
271             if (timestamp.compareTo(launcherTimeStamp) > 0 &&
272                     shouldAdd(projs[i], launcherTimeStamp, timestamp))
273                 projects.add(projs[i]);
274         }
275     }
276
277     private static void handleSelectedPlugins(String JavaDoc timeStamp, String JavaDoc value, ArrayList JavaDoc projects) {
278         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(value, ","); //$NON-NLS-1$
279
while(tokenizer.hasMoreTokens()) {
280             value = tokenizer.nextToken();
281             int index = value.indexOf('@');
282             String JavaDoc id = index > 0 ? value.substring(0, index) : value;
283             IPluginModelBase base = PluginRegistry.findModel(id);
284             if (base != null) {
285                 IResource res = base.getUnderlyingResource();
286                 if (res != null) {
287                     IProject project = res.getProject();
288                     String JavaDoc projTimeStamp = getTimeStamp(project);
289                     if (projTimeStamp.compareTo(timeStamp) > 0 &&
290                             shouldAdd(project, timeStamp, projTimeStamp))
291                         projects.add(project);
292                 }
293             }
294         }
295     }
296
297     private static void handleDeselectedPlugins(String JavaDoc launcherTimeStamp, String JavaDoc value, ArrayList JavaDoc projects) {
298         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(value, ","); //$NON-NLS-1$
299
HashSet JavaDoc deSelectedProjs = new HashSet JavaDoc();
300         while (tokenizer.hasMoreTokens())
301             deSelectedProjs.add(tokenizer.nextToken());
302
303         IProject[] projs = ResourcesPlugin.getWorkspace().getRoot().getProjects();
304         for (int i = 0; i < projs.length; i++) {
305             if (!WorkspaceModelManager.isPluginProject(projs[i]))
306                 continue;
307             IPluginModelBase base = PluginRegistry.findModel(projs[i]);
308             if (base == null || base != null && deSelectedProjs.contains(base.getPluginBase().getId()))
309                 continue;
310             String JavaDoc timestamp = getTimeStamp(projs[i]);
311             if (timestamp.compareTo(launcherTimeStamp) > 0 &&
312                     shouldAdd(projs[i], launcherTimeStamp, timestamp))
313                 projects.add(projs[i]);
314         }
315     }
316
317     public static final void shutdown() {
318         if (fLastRun == null)
319             return;
320         FileOutputStream JavaDoc stream = null;
321         try {
322             stream = new FileOutputStream JavaDoc(new File JavaDoc(getDirectory(), FILE_NAME));
323             fLastRun.store(stream, "Cached timestamps"); //$NON-NLS-1$
324
stream.flush();
325             stream.close();
326         } catch (IOException JavaDoc e) {
327             PDECore.logException(e);
328         } finally {
329             try {
330                 if (stream != null)
331                     stream.close();
332             } catch (IOException JavaDoc e1) {
333             }
334         }
335     }
336
337     private static File JavaDoc getDirectory() {
338         IPath path = PDECore.getDefault().getStateLocation().append(".cache"); //$NON-NLS-1$
339
File JavaDoc directory = new File JavaDoc(path.toOSString());
340         if (!directory.exists() || !directory.isDirectory())
341             directory.mkdirs();
342         return directory;
343     }
344
345     private static Properties JavaDoc getLastRun() {
346         if (fLastRun == null) {
347             fLastRun = new Properties JavaDoc();
348             FileInputStream JavaDoc fis = null;
349             try {
350                 File JavaDoc file = new File JavaDoc(getDirectory(), FILE_NAME);
351                 if (file.exists()) {
352                     fis = new FileInputStream JavaDoc(file);
353                     fLastRun.load(fis);
354                     fis.close();
355                 }
356             } catch (IOException JavaDoc e) {
357                 PDECore.logException(e);
358             } finally {
359                 try {
360                     if (fis != null)
361                         fis.close();
362                 } catch (IOException JavaDoc e1) {
363                 }
364             }
365         }
366         return fLastRun;
367     }
368
369     private static boolean shouldAdd(IProject proj, String JavaDoc launcherTS, String JavaDoc fileSystemTS) {
370         String JavaDoc projTS = (String JavaDoc)getLastRun().get(proj.getName());
371         if (projTS == null)
372             return true;
373         return ((projTS.compareTo(launcherTS) < 0) || (projTS.compareTo(fileSystemTS) < 0));
374     }
375
376     public static boolean requiresUI(ILaunchConfiguration configuration) {
377         try {
378             String JavaDoc projectID = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
379
if (projectID.length() > 0) {
380                 IResource project = PDEPlugin.getWorkspace().getRoot().findMember(projectID);
381                 if (project instanceof IProject) {
382                     IPluginModelBase model = PluginRegistry.findModel((IProject)project);
383                     if (model != null) {
384                         Set JavaDoc plugins = DependencyManager.getSelfAndDependencies(model);
385                         return plugins.contains("org.eclipse.swt"); //$NON-NLS-1$
386
}
387                 }
388             }
389         } catch (CoreException e) {
390         }
391         return true;
392     }
393
394     public static boolean clearWorkspaceLog(String JavaDoc workspace) {
395         File JavaDoc logFile = new File JavaDoc(workspace, ".metadata" + File.separator + ".log"); //$NON-NLS-1$ //$NON-NLS-2$
396
if(logFile != null && logFile.exists()) {
397             return logFile.delete();
398         }
399         return true;
400     }
401
402     public static IStatus createErrorStatus(String JavaDoc message) {
403         return new Status(
404                 IStatus.ERROR,
405                 PDEPlugin.getPluginId(),
406                 IStatus.OK,
407                 message,
408                 null);
409     }
410
411 }
412
Popular Tags