KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > ui > actions > OverrideMethodsAction


1 /*******************************************************************************
2  * Copyright (c) 2000, 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.ui.actions;
12
13 import java.lang.reflect.InvocationTargetException JavaDoc;
14 import java.util.ArrayList JavaDoc;
15
16 import org.eclipse.core.runtime.CoreException;
17
18 import org.eclipse.core.resources.IWorkspaceRunnable;
19
20 import org.eclipse.swt.widgets.Shell;
21
22 import org.eclipse.jface.dialogs.MessageDialog;
23 import org.eclipse.jface.operation.IRunnableContext;
24 import org.eclipse.jface.viewers.IStructuredSelection;
25 import org.eclipse.jface.window.Window;
26
27 import org.eclipse.jface.text.IRewriteTarget;
28 import org.eclipse.jface.text.ITextSelection;
29
30 import org.eclipse.ui.IEditorPart;
31 import org.eclipse.ui.IWorkbenchSite;
32 import org.eclipse.ui.PlatformUI;
33
34 import org.eclipse.jdt.core.ICompilationUnit;
35 import org.eclipse.jdt.core.IType;
36 import org.eclipse.jdt.core.JavaModelException;
37 import org.eclipse.jdt.core.dom.ASTParser;
38 import org.eclipse.jdt.core.dom.CompilationUnit;
39 import org.eclipse.jdt.core.dom.IMethodBinding;
40 import org.eclipse.jdt.core.dom.ITypeBinding;
41
42 import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
43 import org.eclipse.jdt.internal.corext.dom.ASTNodes;
44 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
45
46 import org.eclipse.jdt.ui.JavaUI;
47
48 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
49 import org.eclipse.jdt.internal.ui.JavaPlugin;
50 import org.eclipse.jdt.internal.ui.actions.ActionMessages;
51 import org.eclipse.jdt.internal.ui.actions.ActionUtil;
52 import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
53 import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
54 import org.eclipse.jdt.internal.ui.dialogs.OverrideMethodDialog;
55 import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
56 import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
57 import org.eclipse.jdt.internal.ui.util.ElementValidator;
58 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
59
60 /**
61  * Adds unimplemented methods of a type. The action opens a dialog from which the user can
62  * choose the methods to be added.
63  * <p>
64  * Will open the parent compilation unit in a Java editor. The result is unsaved, so the
65  * user can decide if the changes are acceptable.
66  * <p>
67  * The action is applicable to structured selections containing elements of type
68  * {@link org.eclipse.jdt.core.IType}.
69  *
70  * <p>
71  * This class may be instantiated; it is not intended to be subclassed.
72  * </p>
73  *
74  * @since 2.0
75  */

76 public class OverrideMethodsAction extends SelectionDispatchAction {
77
78     /** The dialog title */
79     private static final String JavaDoc DIALOG_TITLE= ActionMessages.OverrideMethodsAction_error_title;
80
81     /** The compilation unit editor */
82     private CompilationUnitEditor fEditor;
83
84     /**
85      * Note: This constructor is for internal use only. Clients should not call this
86      * constructor.
87      * @param editor the compilation unit editor
88      */

89     public OverrideMethodsAction(final CompilationUnitEditor editor) {
90         this(editor.getEditorSite());
91         fEditor= editor;
92         setEnabled(checkEnabledEditor());
93     }
94
95     /**
96      * Creates a new override method action.
97      * <p>
98      * The action requires that the selection provided by the site's selection provider is
99      * of type {@link org.eclipse.jface.viewers.IStructuredSelection}.
100      *
101      * @param site the workbench site providing context information for this action
102      */

103     public OverrideMethodsAction(final IWorkbenchSite site) {
104         super(site);
105         setText(ActionMessages.OverrideMethodsAction_label);
106         setDescription(ActionMessages.OverrideMethodsAction_description);
107         setToolTipText(ActionMessages.OverrideMethodsAction_tooltip);
108         PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION);
109     }
110
111     private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
112         if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
113             final IType type= (IType) selection.getFirstElement();
114             return type.getCompilationUnit() != null && !type.isInterface();
115         }
116         if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
117             return true;
118         return false;
119     }
120
121     private boolean checkEnabledEditor() {
122         return fEditor != null && SelectionConverter.canOperateOn(fEditor);
123     }
124
125     private String JavaDoc getDialogTitle() {
126         return DIALOG_TITLE;
127     }
128
129     private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
130         final Object JavaDoc[] elements= selection.toArray();
131         if (elements.length == 1 && (elements[0] instanceof IType)) {
132             final IType type= (IType) elements[0];
133             if (type.getCompilationUnit() != null && !type.isInterface()) {
134                 return type;
135             }
136         } else if (elements[0] instanceof ICompilationUnit) {
137             final IType type= ((ICompilationUnit) elements[0]).findPrimaryType();
138             if (type != null && !type.isInterface())
139                 return type;
140         }
141         return null;
142     }
143
144     /*
145      * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
146      */

147     public void run(IStructuredSelection selection) {
148         try {
149             final IType type= getSelectedType(selection);
150             if (type == null) {
151                 MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_not_applicable);
152                 notifyResult(false);
153                 return;
154             }
155             if (!ElementValidator.check(type, getShell(), getDialogTitle(), false) || !ActionUtil.isEditable(getShell(), type)) {
156                 notifyResult(false);
157                 return;
158             }
159             run(getShell(), type);
160         } catch (CoreException exception) {
161             ExceptionHandler.handle(exception, getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_error_actionfailed);
162         }
163     }
164
165     /*
166      * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
167      */

168     public void run(ITextSelection selection) {
169         try {
170             final IType type= SelectionConverter.getTypeAtOffset(fEditor);
171             if (type != null) {
172                 if (!ElementValidator.check(type, getShell(), getDialogTitle(), false) || !ActionUtil.isEditable(fEditor, getShell(), type)) {
173                     notifyResult(false);
174                     return;
175                 }
176                 if (type.isAnnotation()) {
177                     MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_annotation_not_applicable);
178                     notifyResult(false);
179                     return;
180                 }
181                 if (type.isInterface()) {
182                     MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_interface_not_applicable);
183                     notifyResult(false);
184                     return;
185                 }
186                 run(getShell(), type);
187             } else {
188                 MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_not_applicable);
189             }
190         } catch (JavaModelException e) {
191             ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
192         } catch (CoreException e) {
193             ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_error_actionfailed);
194         }
195     }
196
197     private void run(Shell shell, IType type) throws CoreException {
198         final OverrideMethodDialog dialog= new OverrideMethodDialog(shell, fEditor, type, false);
199         if (!dialog.hasMethodsToOverride()) {
200             MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
201             notifyResult(false);
202             return;
203         }
204         if (dialog.open() != Window.OK) {
205             notifyResult(false);
206             return;
207         }
208             
209         final Object JavaDoc[] selected= dialog.getResult();
210         if (selected == null) {
211             notifyResult(false);
212             return;
213         }
214         
215         ArrayList JavaDoc methods= new ArrayList JavaDoc();
216         for (int i= 0; i < selected.length; i++) {
217             Object JavaDoc elem= selected[i];
218             if (elem instanceof IMethodBinding) {
219                 methods.add(elem);
220             }
221         }
222         IMethodBinding[] methodToOverride= (IMethodBinding[]) methods.toArray(new IMethodBinding[methods.size()]);
223
224         
225         final IEditorPart editor= JavaUI.openInEditor(type.getCompilationUnit());
226         final IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
227         if (target != null)
228             target.beginCompoundChange();
229         try {
230             CompilationUnit astRoot= dialog.getCompilationUnit();
231             final ITypeBinding typeBinding= ASTNodes.getTypeBinding(astRoot, type);
232             int insertPos= dialog.getInsertOffset();
233             
234             AddUnimplementedMethodsOperation operation= (AddUnimplementedMethodsOperation) createRunnable(astRoot, typeBinding, methodToOverride, insertPos, dialog.getGenerateComment());
235             IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow();
236             if (context == null)
237                 context= new BusyIndicatorRunnableContext();
238             PlatformUI.getWorkbench().getProgressService().runInUI(context, new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()), operation.getSchedulingRule());
239             final String JavaDoc[] created= operation.getCreatedMethods();
240             if (created == null || created.length == 0)
241                 MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
242         } catch (InvocationTargetException JavaDoc exception) {
243             ExceptionHandler.handle(exception, shell, getDialogTitle(), null);
244         } catch (InterruptedException JavaDoc exception) {
245             // Do nothing. Operation has been canceled by user.
246
} finally {
247             if (target != null)
248                 target.endCompoundChange();
249         }
250         notifyResult(true);
251     }
252
253     /**
254      * Returns a runnable that creates the method stubs for overridden methods.
255      *
256      * @param astRoot the AST of the compilation unit to work on. The AST must have been created from a {@link ICompilationUnit}, that
257      * means {@link ASTParser#setSource(ICompilationUnit)} was used.
258      * @param type the binding of the type to add the new methods to. The type binding must correspond to a type declaration in the AST.
259      * @param methodToOverride the bindings of methods to override or <code>null</code> to implement all unimplemented, abstract methods from super types.
260      * @param insertPos a hint for a location in the source where to insert the new methods or <code>-1</code> to use the default behavior.
261      * @param createComments if set, comments will be added to the new methods.
262      * @return returns a runnable that creates the methods stubs.
263      * @throws IllegalArgumentException a {@link IllegalArgumentException} is thrown if the AST passed has not been created from a {@link ICompilationUnit}.
264      *
265      * @since 3.2
266      */

267     public static IWorkspaceRunnable createRunnable(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] methodToOverride, int insertPos, boolean createComments) {
268         AddUnimplementedMethodsOperation operation= new AddUnimplementedMethodsOperation(astRoot, type, methodToOverride, insertPos, true, true, false);
269         operation.setCreateComments(createComments);
270         return operation;
271     }
272
273     /*
274      * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
275      */

276     public void selectionChanged(IStructuredSelection selection) {
277         try {
278             setEnabled(canEnable(selection));
279         } catch (JavaModelException exception) {
280             if (JavaModelUtil.isExceptionToBeLogged(exception))
281                 JavaPlugin.log(exception);
282             setEnabled(false);
283         }
284     }
285
286     /*
287      * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
288      */

289     public void selectionChanged(ITextSelection selection) {
290         // Do nothing
291
}
292 }
293
Popular Tags