KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > compare > JavaAddElementFromHistoryImpl


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.compare;
12
13 import java.lang.reflect.InvocationTargetException JavaDoc;
14 import java.util.List JavaDoc;
15 import java.util.Map JavaDoc;
16 import java.util.ResourceBundle JavaDoc;
17
18 import org.eclipse.core.runtime.Assert;
19 import org.eclipse.core.runtime.CoreException;
20 import org.eclipse.core.runtime.IPath;
21 import org.eclipse.core.runtime.IStatus;
22
23 import org.eclipse.core.filebuffers.FileBuffers;
24 import org.eclipse.core.filebuffers.ITextFileBuffer;
25 import org.eclipse.core.filebuffers.ITextFileBufferManager;
26 import org.eclipse.core.filebuffers.LocationKind;
27
28 import org.eclipse.core.resources.IFile;
29
30 import org.eclipse.swt.widgets.Shell;
31
32 import org.eclipse.jface.dialogs.MessageDialog;
33 import org.eclipse.jface.viewers.ISelection;
34 import org.eclipse.jface.viewers.IStructuredSelection;
35
36 import org.eclipse.jface.text.IDocument;
37 import org.eclipse.jface.text.TextUtilities;
38
39 import org.eclipse.ui.IEditorInput;
40
41 import org.eclipse.compare.EditionSelectionDialog;
42 import org.eclipse.compare.IStreamContentAccessor;
43 import org.eclipse.compare.ITypedElement;
44 import org.eclipse.compare.structuremergeviewer.DocumentRangeNode;
45
46 import org.eclipse.jdt.core.ICompilationUnit;
47 import org.eclipse.jdt.core.IJavaProject;
48 import org.eclipse.jdt.core.IMember;
49 import org.eclipse.jdt.core.IParent;
50 import org.eclipse.jdt.core.IType;
51 import org.eclipse.jdt.core.dom.ASTNode;
52 import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration;
53 import org.eclipse.jdt.core.dom.BodyDeclaration;
54 import org.eclipse.jdt.core.dom.CompilationUnit;
55 import org.eclipse.jdt.core.dom.EnumDeclaration;
56 import org.eclipse.jdt.core.dom.FieldDeclaration;
57 import org.eclipse.jdt.core.dom.ImportDeclaration;
58 import org.eclipse.jdt.core.dom.PackageDeclaration;
59 import org.eclipse.jdt.core.dom.TypeDeclaration;
60 import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
61 import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
62
63 import org.eclipse.jdt.internal.corext.dom.ASTNodes;
64 import org.eclipse.jdt.internal.corext.util.Resources;
65
66 import org.eclipse.jdt.ui.IWorkingCopyManager;
67
68 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
69 import org.eclipse.jdt.internal.ui.JavaPlugin;
70 import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
71 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
72
73
74 class JavaAddElementFromHistoryImpl extends JavaHistoryActionImpl {
75     
76     private static final String JavaDoc BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.AddFromHistoryAction"; //$NON-NLS-1$
77

78     JavaAddElementFromHistoryImpl() {
79         super(true);
80     }
81     
82     public void run(ISelection selection) {
83         
84         String JavaDoc errorTitle= CompareMessages.AddFromHistory_title;
85         String JavaDoc errorMessage= CompareMessages.AddFromHistory_internalErrorMessage;
86         Shell shell= getShell();
87         
88         ICompilationUnit cu= null;
89         IParent parent= null;
90         IMember input= null;
91         
92         // analyze selection
93
if (selection.isEmpty()) {
94             // no selection: we try to use the editor's input
95
JavaEditor editor= getEditor();
96             if (editor != null) {
97                 IEditorInput editorInput= editor.getEditorInput();
98                 IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
99                 if (manager != null) {
100                     cu= manager.getWorkingCopy(editorInput);
101                     parent= cu;
102                 }
103             }
104         } else {
105             input= getEditionElement(selection);
106             if (input != null) {
107                 cu= input.getCompilationUnit();
108                 parent= input;
109                 input= null;
110
111             } else {
112                 if (selection instanceof IStructuredSelection) {
113                     Object JavaDoc o= ((IStructuredSelection)selection).getFirstElement();
114                     if (o instanceof ICompilationUnit) {
115                         cu= (ICompilationUnit) o;
116                         parent= cu;
117                     }
118                 }
119             }
120         }
121         
122         if (parent == null || cu == null) {
123             String JavaDoc invalidSelectionMessage= CompareMessages.AddFromHistory_invalidSelectionMessage;
124             MessageDialog.openInformation(shell, errorTitle, invalidSelectionMessage);
125             return;
126         }
127         
128         IFile file= getFile(parent);
129         if (file == null) {
130             MessageDialog.openError(shell, errorTitle, errorMessage);
131             return;
132         }
133                 
134         boolean inEditor= beingEdited(file);
135
136         IStatus status= Resources.makeCommittable(file, shell);
137         if (!status.isOK()) {
138             return;
139         }
140         
141         // get the document where to insert the text
142
IPath path= file.getFullPath();
143         ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
144         ITextFileBuffer textFileBuffer= null;
145         try {
146             bufferManager.connect(path, LocationKind.IFILE, null);
147             textFileBuffer= bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
148             IDocument document= textFileBuffer.getDocument();
149             
150             // configure EditionSelectionDialog and let user select an edition
151
ITypedElement target= new JavaTextBufferNode(file, document, inEditor);
152             ITypedElement[] editions= buildEditions(target, file);
153                                             
154             ResourceBundle JavaDoc bundle= ResourceBundle.getBundle(BUNDLE_NAME);
155             EditionSelectionDialog d= new EditionSelectionDialog(shell, bundle);
156             d.setAddMode(true);
157             d.setHelpContextId(IJavaHelpContextIds.ADD_ELEMENT_FROM_HISTORY_DIALOG);
158             ITypedElement selected= d.selectEdition(target, editions, parent);
159             if (selected == null)
160                 return; // user cancel
161

162             ICompilationUnit cu2= cu;
163             if (parent instanceof IMember)
164                 cu2= ((IMember)parent).getCompilationUnit();
165             
166             CompilationUnit root= parsePartialCompilationUnit(cu2);
167             ASTRewrite rewriter= ASTRewrite.create(root.getAST());
168             
169             ITypedElement[] results= d.getSelection();
170             for (int i= 0; i < results.length; i++) {
171                 
172                 // create an AST node
173
ASTNode newNode= createASTNode(rewriter, results[i], TextUtilities.getDefaultLineDelimiter(document), cu.getJavaProject());
174                 if (newNode == null) {
175                     MessageDialog.openError(shell, errorTitle, errorMessage);
176                     return;
177                 }
178                 
179                 // now determine where to put the new node
180
if (newNode instanceof PackageDeclaration) {
181                     rewriter.set(root, CompilationUnit.PACKAGE_PROPERTY, newNode, null);
182                     
183                 } else if (newNode instanceof ImportDeclaration) {
184                     ListRewrite lw= rewriter.getListRewrite(root, CompilationUnit.IMPORTS_PROPERTY);
185                     lw.insertFirst(newNode, null);
186                     
187                 } else { // class, interface, enum, annotation, method, field
188

189                     if (parent instanceof ICompilationUnit) { // top level
190
ListRewrite lw= rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
191                         int index= ASTNodes.getInsertionIndex((BodyDeclaration)newNode, root.types());
192                         lw.insertAt(newNode, index, null);
193                         
194                     } else if (parent instanceof IType) {
195                         ASTNode declaration= getBodyContainer(root, (IType)parent);
196                         if (declaration instanceof TypeDeclaration || declaration instanceof AnnotationTypeDeclaration) {
197                             List JavaDoc container= ASTNodes.getBodyDeclarations(declaration);
198                             int index= ASTNodes.getInsertionIndex((BodyDeclaration)newNode, container);
199                             ListRewrite lw= rewriter.getListRewrite(declaration, ASTNodes.getBodyDeclarationsProperty(declaration));
200                             lw.insertAt(newNode, index, null);
201                         } else if (declaration instanceof EnumDeclaration) {
202                             List JavaDoc container= ((EnumDeclaration)declaration).enumConstants();
203                             int index= ASTNodes.getInsertionIndex((FieldDeclaration)newNode, container);
204                             ListRewrite lw= rewriter.getListRewrite(declaration, EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
205                             lw.insertAt(newNode, index, null);
206                         }
207                     } else {
208                         JavaPlugin.logErrorMessage("JavaAddElementFromHistoryImpl: unknown container " + parent); //$NON-NLS-1$
209
}
210                     
211                 }
212             }
213             
214             Map JavaDoc options= null;
215             IJavaProject javaProject= cu2.getJavaProject();
216             if (javaProject != null)
217                 options= javaProject.getOptions(true);
218             applyChanges(rewriter, document, textFileBuffer, shell, inEditor, options);
219
220         } catch(InvocationTargetException JavaDoc ex) {
221             ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
222             
223         } catch(InterruptedException JavaDoc ex) {
224             // shouldn't be called because is not cancelable
225
Assert.isTrue(false);
226             
227         } catch(CoreException ex) {
228             ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
229             
230         } finally {
231             try {
232                 if (textFileBuffer != null)
233                     bufferManager.disconnect(path, LocationKind.IFILE, null);
234             } catch (CoreException e) {
235                 JavaPlugin.log(e);
236             }
237         }
238     }
239     
240     /**
241      * Creates a place holder ASTNode for the given element.
242      * @param rewriter
243      * @param element
244      * @param delimiter the line delimiter
245      * @param project
246      * @return a ASTNode or null
247      * @throws CoreException
248      */

249     private ASTNode createASTNode(ASTRewrite rewriter, ITypedElement element, String JavaDoc delimiter, IJavaProject project) throws CoreException {
250         if (element instanceof IStreamContentAccessor) {
251             String JavaDoc content= JavaCompareUtilities.readString((IStreamContentAccessor)element);
252             if (content != null) {
253                 content= trimTextBlock(content, delimiter, project);
254                 if (content != null) {
255                     int type= getPlaceHolderType(element);
256                     if (type != -1)
257                         return rewriter.createStringPlaceholder(content, type);
258                 }
259             }
260         }
261         return null;
262     }
263     
264     /**
265      * Returns the corresponding place holder type for the given element.
266      * @return a place holder type (see ASTRewrite) or -1 if there is no corresponding placeholder
267      */

268     private int getPlaceHolderType(ITypedElement element) {
269         
270         if (element instanceof DocumentRangeNode) {
271             JavaNode jn= (JavaNode) element;
272             switch (jn.getTypeCode()) {
273                 
274             case JavaNode.PACKAGE:
275                 return ASTNode.PACKAGE_DECLARATION;
276
277             case JavaNode.CLASS:
278             case JavaNode.INTERFACE:
279                 return ASTNode.TYPE_DECLARATION;
280                 
281             case JavaNode.ENUM:
282                 return ASTNode.ENUM_DECLARATION;
283                 
284             case JavaNode.ANNOTATION:
285                 return ASTNode.ANNOTATION_TYPE_DECLARATION;
286                 
287             case JavaNode.CONSTRUCTOR:
288             case JavaNode.METHOD:
289                 return ASTNode.METHOD_DECLARATION;
290                 
291             case JavaNode.FIELD:
292                 return ASTNode.FIELD_DECLARATION;
293                 
294             case JavaNode.INIT:
295                 return ASTNode.INITIALIZER;
296
297             case JavaNode.IMPORT:
298             case JavaNode.IMPORT_CONTAINER:
299                 return ASTNode.IMPORT_DECLARATION;
300
301             case JavaNode.CU:
302                 return ASTNode.COMPILATION_UNIT;
303             }
304         }
305         return -1;
306     }
307
308     protected boolean isEnabled(ISelection selection) {
309         
310         if (selection.isEmpty()) {
311             JavaEditor editor= getEditor();
312             if (editor != null) {
313                 // we check whether editor shows CompilationUnit
314
IEditorInput editorInput= editor.getEditorInput();
315                 IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
316                 return manager.getWorkingCopy(editorInput) != null;
317             }
318             return false;
319         }
320         
321         if (selection instanceof IStructuredSelection) {
322             Object JavaDoc o= ((IStructuredSelection)selection).getFirstElement();
323             if (o instanceof ICompilationUnit)
324                 return true;
325         }
326         
327         return super.isEnabled(selection);
328     }
329 }
330
Popular Tags