KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > debug > ui > breakpoints > AddExceptionDialog


1 /*******************************************************************************
2  * Copyright (c) 2006, 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.debug.ui.breakpoints;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.Comparator JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.Map JavaDoc;
19
20 import org.eclipse.core.runtime.CoreException;
21 import org.eclipse.core.runtime.IAdaptable;
22 import org.eclipse.core.runtime.IProgressMonitor;
23 import org.eclipse.core.runtime.IStatus;
24 import org.eclipse.core.runtime.NullProgressMonitor;
25 import org.eclipse.core.runtime.Platform;
26 import org.eclipse.core.runtime.Status;
27 import org.eclipse.jdt.core.IJavaElement;
28 import org.eclipse.jdt.core.IPackageFragmentRoot;
29 import org.eclipse.jdt.core.IType;
30 import org.eclipse.jdt.core.ITypeHierarchy;
31 import org.eclipse.jdt.core.JavaCore;
32 import org.eclipse.jdt.core.JavaModelException;
33 import org.eclipse.jdt.core.WorkingCopyOwner;
34 import org.eclipse.jdt.core.search.IJavaSearchConstants;
35 import org.eclipse.jdt.core.search.SearchEngine;
36 import org.eclipse.jdt.core.search.SearchPattern;
37 import org.eclipse.jdt.core.search.TypeNameMatch;
38 import org.eclipse.jdt.core.search.TypeNameMatchRequestor;
39 import org.eclipse.jdt.internal.debug.ui.IJavaDebugHelpContextIds;
40 import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
41 import org.eclipse.jdt.internal.debug.ui.SWTFactory;
42 import org.eclipse.jdt.launching.IVMInstall;
43 import org.eclipse.jdt.launching.IVMInstallType;
44 import org.eclipse.jdt.launching.JavaRuntime;
45 import org.eclipse.jdt.launching.LibraryLocation;
46 import org.eclipse.jdt.ui.JavaElementLabels;
47 import org.eclipse.jface.dialogs.IDialogSettings;
48 import org.eclipse.jface.resource.ImageDescriptor;
49 import org.eclipse.jface.viewers.ILabelDecorator;
50 import org.eclipse.jface.viewers.ILabelProviderListener;
51 import org.eclipse.jface.viewers.LabelProvider;
52 import org.eclipse.swt.events.SelectionEvent;
53 import org.eclipse.swt.events.SelectionListener;
54 import org.eclipse.swt.graphics.Image;
55 import org.eclipse.swt.layout.GridData;
56 import org.eclipse.swt.widgets.Button;
57 import org.eclipse.swt.widgets.Composite;
58 import org.eclipse.swt.widgets.Control;
59 import org.eclipse.ui.IMemento;
60 import org.eclipse.ui.PlatformUI;
61 import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog;
62 import org.eclipse.ui.model.IWorkbenchAdapter;
63
64 import com.ibm.icu.text.MessageFormat;
65
66 /**
67  * This is a specialization of <code>FilteredItemsSelectionDialog</code> used to present
68  * users with a listing of exceptions to select to create exception breakpoints on
69  *
70  * @since 3.3
71  *
72  */

73 public class AddExceptionDialog extends FilteredItemsSelectionDialog {
74     
75     /**
76      * A Util class that is used to create labels for the types of the main list in the add exception dialog
77      */

78     private static class TypeInfoUtil {
79
80         private Map JavaDoc fLib2Name= new HashMap JavaDoc();
81         private String JavaDoc[] fInstallLocations;
82         private String JavaDoc[] fVMNames;
83
84         public TypeInfoUtil() {
85             List JavaDoc locations= new ArrayList JavaDoc();
86             List JavaDoc labels= new ArrayList JavaDoc();
87             IVMInstallType[] installs= JavaRuntime.getVMInstallTypes();
88             for (int i= 0; i < installs.length; i++) {
89                 processVMInstallType(installs[i], locations, labels);
90             }
91             fInstallLocations= (String JavaDoc[]) locations.toArray(new String JavaDoc[locations.size()]);
92             fVMNames= (String JavaDoc[]) labels.toArray(new String JavaDoc[labels.size()]);
93
94         }
95         private void processVMInstallType(IVMInstallType installType, List JavaDoc locations, List JavaDoc labels) {
96             if (installType != null) {
97                 IVMInstall[] installs= installType.getVMInstalls();
98                 boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS());
99                 final String JavaDoc HOME_SUFFIX= "/Home"; //$NON-NLS-1$
100
for (int i= 0; i < installs.length; i++) {
101                     String JavaDoc label= getFormattedLabel(installs[i].getName());
102                     LibraryLocation[] libLocations= installs[i].getLibraryLocations();
103                     if (libLocations != null) {
104                         processLibraryLocation(libLocations, label);
105                     } else {
106                         String JavaDoc filePath= installs[i].getInstallLocation().getAbsolutePath();
107                         // on MacOS X install locations end in an additional
108
// "/Home" segment; remove it
109
if (isMac && filePath.endsWith(HOME_SUFFIX))
110                             filePath= filePath.substring(0, filePath.length() - HOME_SUFFIX.length() + 1);
111                         locations.add(filePath);
112                         labels.add(label);
113                     }
114                 }
115             }
116         }
117         private void processLibraryLocation(LibraryLocation[] libLocations, String JavaDoc label) {
118             for (int l= 0; l < libLocations.length; l++) {
119                 LibraryLocation location= libLocations[l];
120                 fLib2Name.put(location.getSystemLibraryPath().toOSString(), label);
121             }
122         }
123
124         private String JavaDoc getFormattedLabel(String JavaDoc name) {
125             return MessageFormat.format(BreakpointMessages.AddExceptionDialog_12, new String JavaDoc[] {name});
126         }
127         /**
128          * Returns the simple name of the underlying type from the type name match
129          * @param element
130          * @return
131          */

132         public String JavaDoc getText(TypeNameMatch element) {
133             return element.getSimpleTypeName();
134         }
135         /**
136          * Returns the qualified text for the specified type name match
137          * @param type
138          * @return the qualified text for the specified type name match
139          */

140         public String JavaDoc getQualifiedText(TypeNameMatch type) {
141             StringBuffer JavaDoc result= new StringBuffer JavaDoc();
142             result.append(type.getSimpleTypeName());
143             String JavaDoc containerName= type.getTypeContainerName();
144             result.append(JavaElementLabels.CONCAT_STRING);
145             if (containerName.length() > 0) {
146                 result.append(containerName);
147             } else {
148                 result.append(BreakpointMessages.AddExceptionDialog_11);
149             }
150             return result.toString();
151         }
152         /**
153          * Returns the fully qualified text for the specified type name match
154          * @param type
155          * @return the fully qualified text for the specified type name match
156          */

157         public String JavaDoc getFullyQualifiedText(TypeNameMatch type) {
158             StringBuffer JavaDoc result= new StringBuffer JavaDoc();
159             result.append(type.getSimpleTypeName());
160             String JavaDoc containerName= type.getTypeContainerName();
161             if (containerName.length() > 0) {
162                 result.append(JavaElementLabels.CONCAT_STRING);
163                 result.append(containerName);
164             }
165             result.append(JavaElementLabels.CONCAT_STRING);
166             result.append(getContainerName(type));
167             return result.toString();
168         }
169         /**
170          * Returns the qualification text for an element, more specifically appends the package information to the element label
171          * @param type
172          * @return the qualification text for an element
173          */

174         public String JavaDoc getQualificationText(TypeNameMatch type) {
175             StringBuffer JavaDoc result= new StringBuffer JavaDoc();
176             String JavaDoc containerName= type.getTypeContainerName();
177             if (containerName.length() > 0) {
178                 result.append(containerName);
179                 result.append(JavaElementLabels.CONCAT_STRING);
180             }
181             result.append(getContainerName(type));
182             return result.toString();
183         }
184         /**
185          * Returns the package fragment root simple container name from the type name match
186          * @param type
187          * @return the simple text name for the package fragment root for the type name match
188          */

189         private String JavaDoc getContainerName(TypeNameMatch type) {
190             IPackageFragmentRoot root= type.getPackageFragmentRoot();
191             if (root.isExternal()) {
192                 String JavaDoc name= root.getPath().toOSString();
193                 for (int i= 0; i < fInstallLocations.length; i++) {
194                     if (name.startsWith(fInstallLocations[i])) {
195                         return fVMNames[i];
196                     }
197                 }
198                 String JavaDoc lib= (String JavaDoc) fLib2Name.get(name);
199                 if (lib != null)
200                     return lib;
201             }
202             StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
203             JavaElementLabels.getPackageFragmentRootLabel(root, JavaElementLabels.ROOT_QUALIFIED | JavaElementLabels.ROOT_VARIABLE, buf);
204             return buf.toString();
205         }
206     }
207     
208     /**
209      * Collects matching results into the specified content provider
210      */

211     public class ExceptionTypeNameRequestor extends TypeNameMatchRequestor {
212         private AbstractContentProvider fContentProvider;
213         private ItemsFilter fFilter;
214         
215         /**
216          * Constructor
217          * @param provider
218          * @param filter
219          */

220         public ExceptionTypeNameRequestor(AbstractContentProvider provider, ItemsFilter filter) {
221             super();
222             fContentProvider = provider;
223             fFilter = filter;
224         }
225         /**
226          * @see org.eclipse.jdt.core.search.TypeNameMatchRequestor#acceptTypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch)
227          */

228         public void acceptTypeNameMatch(TypeNameMatch match) {
229             fContentProvider.add(match, fFilter);
230         }
231     }
232     
233     /**
234      * Main list label provider
235      */

236     public class ExceptionLabelProvider extends LabelProvider implements ILabelDecorator {
237         HashMap JavaDoc fImageMap = new HashMap JavaDoc();
238         
239         /**
240          * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
241          */

242         public Image getImage(Object JavaDoc element) {
243             IAdaptable type = null;
244             if(element instanceof TypeNameMatch) {
245                 type = ((TypeNameMatch)element).getType();
246             }
247             if(element instanceof IAdaptable) {
248                 type = (IAdaptable) element;
249             }
250             if(type != null) {
251                 IWorkbenchAdapter adapter = (IWorkbenchAdapter) type.getAdapter(IWorkbenchAdapter.class);
252                 if(adapter != null) {
253                     ImageDescriptor descriptor = adapter.getImageDescriptor(type);
254                     Image image = (Image) fImageMap.get(descriptor);
255                     if(image == null) {
256                         image = descriptor.createImage();
257                         fImageMap.put(descriptor, image);
258                     }
259                     return image;
260                 }
261             }
262             return null;
263         }
264         /**
265          * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
266          */

267         public String JavaDoc getText(Object JavaDoc element) {
268             if (!(element instanceof TypeNameMatch)) {
269                 return super.getText(element);
270             }
271             return fTypeInfoUtil.getText((TypeNameMatch) element);
272         }
273         /**
274          * @see org.eclipse.jface.viewers.ILabelDecorator#decorateText(java.lang.String, java.lang.Object)
275          */

276         public String JavaDoc decorateText(String JavaDoc text, Object JavaDoc element) {
277             if (!(element instanceof TypeNameMatch)) {
278                 return null;
279             }
280             return fTypeInfoUtil.getQualifiedText((TypeNameMatch) element);
281         }
282         /**
283          * @see org.eclipse.jface.viewers.BaseLabelProvider#dispose()
284          */

285         public void dispose() {
286             if (fImageMap != null) {
287                 Iterator JavaDoc iterator = fImageMap.values().iterator();
288                 while (iterator.hasNext()) {
289                     Image image = (Image) iterator.next();
290                     image.dispose();
291                 }
292                 fImageMap.clear();
293             }
294             fImageMap = null;
295         }
296         public void addListener(ILabelProviderListener listener) {}
297         public boolean isLabelProperty(Object JavaDoc element, String JavaDoc property) {return false;}
298         public void removeListener(ILabelProviderListener listener) {}
299         public Image decorateImage(Image image, Object JavaDoc element) {return null;}
300         
301     }
302     
303     /**
304      * Provides a label and image for the details area of the dialog
305      */

306     class ExceptionDetailsLabelProvider extends ExceptionLabelProvider {
307         public String JavaDoc getText(Object JavaDoc element) {
308             if (element instanceof TypeNameMatch) {
309                 return fTypeInfoUtil.getQualificationText((TypeNameMatch) element);
310             }
311             return super.getText(element);
312         }
313         /**
314          * Returns the narrowest enclosing <code>IJavaElement</code> which is either
315          * an <code>IType</code> (enclosing) or an <code>IPackageFragment</code> (contained in)
316          * @param type the type to find the enclosing <code>IJavaElement</code> for.
317          * @return the enclosing element or <code>null</code> if none
318          */

319         protected IJavaElement getDeclaringContainer(IType type) {
320             IJavaElement outer = type.getDeclaringType();
321             if(outer == null) {
322                 outer = type.getPackageFragment();
323             }
324             return outer;
325         }
326         /**
327          * @see org.eclipse.jdt.internal.debug.ui.breakpoints.AddExceptionDialog.ExceptionLabelProvider#getImage(java.lang.Object)
328          */

329         public Image getImage(Object JavaDoc element) {
330             if(element instanceof TypeNameMatch) {
331                 return super.getImage(getDeclaringContainer(((TypeNameMatch)element).getType()));
332             }
333             return super.getImage(element);
334         }
335     }
336     
337     /**
338      * Simple items filter
339      */

340     class ExceptionItemsFilter extends ItemsFilter {
341         public boolean isConsistentItem(Object JavaDoc item) {
342             return item instanceof IType;
343         }
344         public boolean matchItem(Object JavaDoc item) {
345             if(item instanceof TypeNameMatch) {
346                 TypeNameMatch tname = (TypeNameMatch) item;
347                 IType type = tname.getType();
348                 if(type != null) {
349 // if(type.getElementName().indexOf("Exception") < 0) { //$NON-NLS-1$
350
// return false;
351
// }
352
return matches(type.getElementName());
353                 }
354             }
355             return false;
356         }
357     }
358     
359     /**
360      * The selection history for the dialog
361      */

362     class ExceptionSelectionHistory extends SelectionHistory {
363         protected Object JavaDoc restoreItemFromMemento(IMemento memento) {
364             IJavaElement element = JavaCore.create(memento.getTextData());
365             return (element instanceof IType ? element : null);
366         }
367         protected void storeItemToMemento(Object JavaDoc item, IMemento memento) {
368             if(item instanceof IType) {
369                 memento.putTextData(((IType) item).getHandleIdentifier());
370             }
371         }
372     }
373     
374     /**
375      * Constants
376      */

377     private static final String JavaDoc SETTINGS_ID = JDIDebugUIPlugin.getUniqueIdentifier() + ".ADD_EXCEPTION_DIALOG"; //$NON-NLS-1$
378
public static final String JavaDoc SETTING_CAUGHT_CHECKED = "caughtChecked"; //$NON-NLS-1$
379
public static final String JavaDoc SETTING_UNCAUGHT_CHECKED = "uncaughtChecked"; //$NON-NLS-1$
380

381      /**
382       * widgets
383       */

384      private Button fCaughtButton;
385      private Button fUncaughtButton;
386      private boolean fCaught = false;
387      private boolean fUncaught = false;
388      
389      private TypeInfoUtil fTypeInfoUtil = null;
390      
391     /**
392      * Constructor
393      */

394     public AddExceptionDialog() {
395         super(JDIDebugUIPlugin.getShell(), false);
396         fTypeInfoUtil = new TypeInfoUtil();
397         setTitle(BreakpointMessages.AddExceptionAction_0);
398         setMessage(BreakpointMessages.AddExceptionAction_1);
399         setInitialPattern("*Exception*"); //$NON-NLS-1$
400
setSelectionHistory(new ExceptionSelectionHistory());
401         ExceptionLabelProvider lp = new ExceptionLabelProvider();
402         setListLabelProvider(lp);
403         setListSelectionLabelDecorator(lp);
404         setDetailsLabelProvider(new ExceptionDetailsLabelProvider());
405     }
406     
407     /* (non-Javadoc)
408      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
409      */

410     protected Control createDialogArea(Composite parent) {
411         Control ctrl = super.createDialogArea(parent);
412         PlatformUI.getWorkbench().getHelpSystem().setHelp(ctrl, IJavaDebugHelpContextIds.ADD_EXCEPTION_DIALOG);
413         return ctrl;
414     }
415
416     /**
417      * Returns if the breakpoint should be set to suspend when the associated exception is thrown, but caught
418      * @return if the breakpoint should be set to suspend when the associated exception is thrown, but caught
419      */

420     public boolean shouldHandleCaughtExceptions() {
421         return fCaught;
422     }
423     
424     /**Returns if the breakpoint should be set to suspend when the associated exception is thrown, but not caught
425      * @return if the breakpoint should be set to suspend when the associated exception is thrown, but not caught
426      */

427     public boolean shouldHandleUncaughtExceptions() {
428         return fUncaught;
429     }
430     
431     /* (non-Javadoc)
432      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createExtendedContentArea(org.eclipse.swt.widgets.Composite)
433      */

434     protected Control createExtendedContentArea(Composite parent) {
435         Composite comp = SWTFactory.createComposite(parent, parent.getFont(), 1, 1, GridData.FILL_HORIZONTAL);
436         fCaughtButton = SWTFactory.createCheckButton(comp, BreakpointMessages.AddExceptionDialog_15, null, getDialogSettings().getBoolean(SETTING_CAUGHT_CHECKED), 1);
437         fCaughtButton.addSelectionListener(new SelectionListener() {
438             public void widgetDefaultSelected(SelectionEvent e) {}
439             public void widgetSelected(SelectionEvent e) {
440                 fCaught = fCaughtButton.getSelection();
441             }
442         });
443         fUncaughtButton = SWTFactory.createCheckButton(comp, BreakpointMessages.AddExceptionDialog_16, null, getDialogSettings().getBoolean(SETTING_UNCAUGHT_CHECKED), 1);
444         fUncaughtButton.addSelectionListener(new SelectionListener() {
445             public void widgetDefaultSelected(SelectionEvent e) {}
446             public void widgetSelected(SelectionEvent e) {
447                 fUncaught = fUncaughtButton.getSelection();
448             }
449         });
450         return comp;
451     }
452
453     /* (non-Javadoc)
454      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#okPressed()
455      */

456     protected void okPressed() {
457         fCaught = fCaughtButton.getSelection();
458         fUncaught = fUncaughtButton.getSelection();
459         IDialogSettings settings = getDialogSettings();
460         settings.put(SETTING_CAUGHT_CHECKED, fCaught);
461         settings.put(SETTING_UNCAUGHT_CHECKED, fUncaught);
462         super.okPressed();
463     }
464
465     /* (non-Javadoc)
466      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createFilter()
467      */

468     protected ItemsFilter createFilter() {
469         return new ExceptionItemsFilter();
470     }
471
472     /* (non-Javadoc)
473      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#fillContentProvider(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.AbstractContentProvider, org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter, org.eclipse.core.runtime.IProgressMonitor)
474      */

475     protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException {
476         if(progressMonitor == null) {
477             progressMonitor = new NullProgressMonitor();
478         }
479         progressMonitor.setTaskName(BreakpointMessages.AddExceptionDialog_10);
480         SearchEngine engine = new SearchEngine((WorkingCopyOwner) null);
481         engine.searchAllTypeNames((char[])null, SearchPattern.R_EXACT_MATCH, (char[])null,
482                 SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.CLASS, SearchEngine.createWorkspaceScope(),
483                 new ExceptionTypeNameRequestor(contentProvider, itemsFilter), IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, progressMonitor);
484     }
485
486     /* (non-Javadoc)
487      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getDialogSettings()
488      */

489     protected IDialogSettings getDialogSettings() {
490         IDialogSettings settings = JDIDebugUIPlugin.getDefault().getDialogSettings();
491         IDialogSettings section = settings.getSection(SETTINGS_ID);
492         if (section == null) {
493             section = settings.addNewSection(SETTINGS_ID);
494             section.put(SETTING_CAUGHT_CHECKED, true);
495             section.put(SETTING_UNCAUGHT_CHECKED, true);
496         }
497         return section;
498     }
499
500     /* (non-Javadoc)
501      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getElementName(java.lang.Object)
502      */

503     public String JavaDoc getElementName(Object JavaDoc item) {
504         if(item instanceof TypeNameMatch) {
505             return ((TypeNameMatch)item).getSimpleTypeName();
506         }
507         return null;
508     }
509
510     /* (non-Javadoc)
511      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getItemsComparator()
512      */

513     protected Comparator JavaDoc getItemsComparator() {
514         Comparator JavaDoc comp = new Comparator JavaDoc() {
515             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
516                 if(o1 instanceof TypeNameMatch && o2 instanceof TypeNameMatch) {
517                     return ((TypeNameMatch)o1).getSimpleTypeName().compareTo(((TypeNameMatch)o2).getSimpleTypeName());
518                 }
519                 return -1;
520             }
521         };
522         return comp;
523     }
524
525     /* (non-Javadoc)
526      * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#validateItem(java.lang.Object)
527      */

528     protected IStatus validateItem(Object JavaDoc item) {
529         if(item instanceof TypeNameMatch) {
530             IType type = ((TypeNameMatch) item).getType();
531             try {
532                 ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
533                 IType curr = type;
534                 while (curr != null) {
535                     if ("java.lang.Throwable".equals(curr.getFullyQualifiedName('.'))) { //$NON-NLS-1$
536
return Status.OK_STATUS;
537                     }
538                     curr = hierarchy.getSuperclass(curr);
539                 }
540             }
541             catch (JavaModelException e) {
542                 JDIDebugUIPlugin.log(e);
543                 return Status.CANCEL_STATUS;
544             }
545         }
546         return new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), BreakpointMessages.AddExceptionDialog_13);
547     }
548
549 }
550
Popular Tags