KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > corext > refactoring > code > IntroduceParameterRefactoring


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  * Felix Pahl (fpahl@web.de) - contributed fix for:
11  * o introduce parameter throws NPE if there are compiler errors
12  * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=48325)
13  *******************************************************************************/

14
15 package org.eclipse.jdt.internal.corext.refactoring.code;
16
17 import java.util.Arrays JavaDoc;
18 import java.util.Collections JavaDoc;
19 import java.util.HashMap JavaDoc;
20 import java.util.LinkedHashSet JavaDoc;
21 import java.util.List JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.util.StringTokenizer JavaDoc;
24
25 import org.eclipse.core.runtime.Assert;
26 import org.eclipse.core.runtime.CoreException;
27 import org.eclipse.core.runtime.IProgressMonitor;
28 import org.eclipse.core.runtime.SubProgressMonitor;
29
30 import org.eclipse.jface.text.TextSelection;
31
32 import org.eclipse.ltk.core.refactoring.Change;
33 import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
34 import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
35 import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
36 import org.eclipse.ltk.core.refactoring.RefactoringStatus;
37 import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
38 import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
39
40 import org.eclipse.jdt.core.ICompilationUnit;
41 import org.eclipse.jdt.core.IJavaElement;
42 import org.eclipse.jdt.core.IMethod;
43 import org.eclipse.jdt.core.JavaModelException;
44 import org.eclipse.jdt.core.dom.ASTNode;
45 import org.eclipse.jdt.core.dom.ArrayInitializer;
46 import org.eclipse.jdt.core.dom.Assignment;
47 import org.eclipse.jdt.core.dom.ClassInstanceCreation;
48 import org.eclipse.jdt.core.dom.Expression;
49 import org.eclipse.jdt.core.dom.FieldAccess;
50 import org.eclipse.jdt.core.dom.IBinding;
51 import org.eclipse.jdt.core.dom.ITypeBinding;
52 import org.eclipse.jdt.core.dom.MethodDeclaration;
53 import org.eclipse.jdt.core.dom.MethodInvocation;
54 import org.eclipse.jdt.core.dom.Name;
55 import org.eclipse.jdt.core.dom.NullLiteral;
56 import org.eclipse.jdt.core.dom.QualifiedName;
57 import org.eclipse.jdt.core.dom.SimpleName;
58 import org.eclipse.jdt.core.refactoring.IJavaRefactorings;
59
60 import org.eclipse.jdt.internal.corext.Corext;
61 import org.eclipse.jdt.internal.corext.SourceRange;
62 import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
63 import org.eclipse.jdt.internal.corext.dom.ASTNodes;
64 import org.eclipse.jdt.internal.corext.dom.Bindings;
65 import org.eclipse.jdt.internal.corext.dom.NodeFinder;
66 import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
67 import org.eclipse.jdt.internal.corext.dom.fragments.ASTFragmentFactory;
68 import org.eclipse.jdt.internal.corext.dom.fragments.IASTFragment;
69 import org.eclipse.jdt.internal.corext.dom.fragments.IExpressionFragment;
70 import org.eclipse.jdt.internal.corext.refactoring.Checks;
71 import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments;
72 import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptor;
73 import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
74 import org.eclipse.jdt.internal.corext.refactoring.ParameterInfo;
75 import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester;
76 import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
77 import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusCodes;
78 import org.eclipse.jdt.internal.corext.refactoring.changes.RefactoringDescriptorChange;
79 import org.eclipse.jdt.internal.corext.refactoring.structure.BodyUpdater;
80 import org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring;
81 import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
82 import org.eclipse.jdt.internal.corext.refactoring.tagging.IDelegateUpdating;
83 import org.eclipse.jdt.internal.corext.util.Messages;
84
85 import org.eclipse.jdt.ui.JavaElementLabels;
86
87 import org.eclipse.jdt.internal.ui.JavaPlugin;
88 import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
89
90 public class IntroduceParameterRefactoring extends ScriptableRefactoring implements IDelegateUpdating {
91
92     private static final String JavaDoc ATTRIBUTE_ARGUMENT= "argument"; //$NON-NLS-1$
93

94     private static final String JavaDoc[] KNOWN_METHOD_NAME_PREFIXES= {"get", "is"}; //$NON-NLS-2$ //$NON-NLS-1$
95

96     private ICompilationUnit fSourceCU;
97     private int fSelectionStart;
98     private int fSelectionLength;
99     
100     private IMethod fMethod;
101     private ChangeSignatureRefactoring fChangeSignatureRefactoring;
102     private ParameterInfo fParameter;
103     private String JavaDoc fParameterName;
104     private RefactoringArguments fArguments;
105
106     private Expression fSelectedExpression;
107     private String JavaDoc[] fExcludedParameterNames;
108     
109     /**
110      * Creates a new introduce parameter refactoring.
111      * @param unit the compilation unit, or <code>null</code> if invoked by scripting
112      * @param selectionStart
113      * @param selectionLength
114      */

115     public IntroduceParameterRefactoring(ICompilationUnit unit, int selectionStart, int selectionLength) {
116         Assert.isTrue(selectionStart >= 0);
117         Assert.isTrue(selectionLength >= 0);
118         fSourceCU= unit;
119         fSelectionStart= selectionStart;
120         fSelectionLength= selectionLength;
121     }
122     
123     // ------------------- IDelegateUpdating ----------------------
124

125     public boolean canEnableDelegateUpdating() {
126         return true;
127     }
128
129     public boolean getDelegateUpdating() {
130         return (fChangeSignatureRefactoring != null) ? fChangeSignatureRefactoring.getDelegateUpdating() : false;
131     }
132
133     public void setDelegateUpdating(boolean updating) {
134         if (fChangeSignatureRefactoring != null)
135             fChangeSignatureRefactoring.setDelegateUpdating(updating);
136     }
137
138     public void setDeprecateDelegates(boolean deprecate) {
139         if (fChangeSignatureRefactoring != null)
140             fChangeSignatureRefactoring.setDeprecateDelegates(deprecate);
141     }
142
143     public boolean getDeprecateDelegates() {
144         return (fChangeSignatureRefactoring != null) ? fChangeSignatureRefactoring.getDeprecateDelegates() : false;
145     }
146
147     // ------------------- /IDelegateUpdating ---------------------
148

149     public String JavaDoc getName() {
150         return RefactoringCoreMessages.IntroduceParameterRefactoring_name;
151     }
152
153     //--- checkActivation
154

155     public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
156         try {
157             pm.beginTask("", 7); //$NON-NLS-1$
158

159             if (! fSourceCU.isStructureKnown())
160                 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_syntax_error);
161             
162             IJavaElement enclosingElement= SelectionConverter.resolveEnclosingElement(fSourceCU, new TextSelection(fSelectionStart, fSelectionLength));
163             if (! (enclosingElement instanceof IMethod))
164                 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_in_method);
165             
166             fMethod= (IMethod) enclosingElement;
167             pm.worked(1);
168
169             RefactoringStatus result= new RefactoringStatus();
170             if (fArguments != null) {
171                 // invoked by script
172
fChangeSignatureRefactoring= new ChangeSignatureRefactoring(null);
173                 result= fChangeSignatureRefactoring.initialize(fArguments);
174                 if (!result.hasFatalError()) {
175                     fChangeSignatureRefactoring.setValidationContext(getValidationContext());
176                     result.merge(fChangeSignatureRefactoring.checkInitialConditions(new SubProgressMonitor(pm, 2)));
177                     if (result.hasFatalError())
178                         return result;
179                 } else {
180                     pm.worked(2);
181                     return result;
182                 }
183             } else {
184                 // first try:
185
fChangeSignatureRefactoring= RefactoringAvailabilityTester.isChangeSignatureAvailable(fMethod) ? new ChangeSignatureRefactoring(fMethod) : null;
186                 if (fChangeSignatureRefactoring == null)
187                     return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_in_method);
188                 fChangeSignatureRefactoring.setValidationContext(getValidationContext());
189                 result.merge(fChangeSignatureRefactoring.checkInitialConditions(new SubProgressMonitor(pm, 1)));
190                 if (result.hasFatalError()) {
191                     RefactoringStatusEntry entry= result.getEntryMatchingSeverity(RefactoringStatus.FATAL);
192                     if (entry.getCode() == RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD || entry.getCode() == RefactoringStatusCodes.METHOD_DECLARED_IN_INTERFACE) {
193                         // second try:
194
IMethod method= (IMethod) entry.getData();
195                         fChangeSignatureRefactoring= RefactoringAvailabilityTester.isChangeSignatureAvailable(method) ? new ChangeSignatureRefactoring(method) : null;
196                         if (fChangeSignatureRefactoring == null) {
197                             String JavaDoc msg= Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_cannot_introduce, entry.getMessage());
198                             return RefactoringStatus.createFatalErrorStatus(msg);
199                         }
200                         result= fChangeSignatureRefactoring.checkInitialConditions(new SubProgressMonitor(pm, 1));
201                         if (result.hasFatalError())
202                             return result;
203                     } else {
204                         return result;
205                     }
206                 } else {
207                     pm.worked(1);
208                 }
209             }
210
211             CompilationUnitRewrite cuRewrite= fChangeSignatureRefactoring.getBaseCuRewrite();
212             if (! cuRewrite.getCu().equals(fSourceCU))
213                 cuRewrite= new CompilationUnitRewrite(fSourceCU); // TODO: should try to avoid throwing away this AST
214

215             initializeSelectedExpression(cuRewrite);
216             pm.worked(1);
217         
218             result.merge(checkSelection(cuRewrite, new SubProgressMonitor(pm, 3)));
219             if (result.hasFatalError())
220                 return result;
221
222             initializeExcludedParameterNames(cuRewrite);
223             
224             addParameterInfo(cuRewrite);
225             
226             fChangeSignatureRefactoring.setBodyUpdater(new BodyUpdater() {
227                 public void updateBody(MethodDeclaration methodDeclaration, CompilationUnitRewrite rewrite, RefactoringStatus updaterResult) {
228                     replaceSelectedExpression(rewrite);
229                 }
230             });
231             
232             return result;
233         } finally {
234             pm.done();
235             if (fChangeSignatureRefactoring != null)
236                 fChangeSignatureRefactoring.setValidationContext(null);
237         }
238     }
239
240     private void addParameterInfo(CompilationUnitRewrite cuRewrite) throws JavaModelException {
241         ITypeBinding typeBinding= Bindings.normalizeForDeclarationUse(fSelectedExpression.resolveTypeBinding(), fSelectedExpression.getAST());
242         String JavaDoc typeName= cuRewrite.getImportRewrite().addImport(typeBinding);
243         String JavaDoc name= fParameterName != null ? fParameterName : guessedParameterName();
244         String JavaDoc defaultValue= fSourceCU.getBuffer().getText(fSelectedExpression.getStartPosition(), fSelectedExpression.getLength());
245         fParameter= ParameterInfo.createInfoForAddedParameter(typeBinding, typeName, name, defaultValue);
246         if (fArguments == null) {
247             List JavaDoc parameterInfos= fChangeSignatureRefactoring.getParameterInfos();
248             int parametersCount= parameterInfos.size();
249             if (parametersCount > 0 && ((ParameterInfo) parameterInfos.get(parametersCount - 1)).isOldVarargs())
250                 parameterInfos.add(parametersCount - 1, fParameter);
251             else
252                 parameterInfos.add(fParameter);
253         }
254     }
255
256     private void replaceSelectedExpression(CompilationUnitRewrite cuRewrite) {
257         if (! fSourceCU.equals(cuRewrite.getCu()))
258             return;
259         // TODO: do for all methodDeclarations and replace matching fragments?
260

261         // cannot use fSelectedExpression here, since it could be from another AST (if method was replaced by overridden):
262
Expression expression= (Expression) NodeFinder.perform(cuRewrite.getRoot(), fSelectedExpression.getStartPosition(), fSelectedExpression.getLength());
263         
264         ASTNode newExpression= cuRewrite.getRoot().getAST().newSimpleName(fParameter.getNewName());
265         String JavaDoc description= RefactoringCoreMessages.IntroduceParameterRefactoring_replace;
266         cuRewrite.getASTRewrite().replace(expression, newExpression, cuRewrite.createGroupDescription(description));
267     }
268
269     private void initializeSelectedExpression(CompilationUnitRewrite cuRewrite) throws JavaModelException {
270         IASTFragment fragment= ASTFragmentFactory.createFragmentForSourceRange(
271                 new SourceRange(fSelectionStart, fSelectionLength), cuRewrite.getRoot(), cuRewrite.getCu());
272         
273         if (! (fragment instanceof IExpressionFragment))
274             return;
275         
276         //TODO: doesn't handle selection of partial Expressions
277
Expression expression= ((IExpressionFragment) fragment).getAssociatedExpression();
278         if (fragment.getStartPosition() != expression.getStartPosition()
279                 || fragment.getLength() != expression.getLength())
280             return;
281         
282         if (Checks.isInsideJavadoc(expression))
283             return;
284         //TODO: exclude invalid selections
285
if (Checks.isEnumCase(expression.getParent()))
286             return;
287         
288         fSelectedExpression= expression;
289     }
290     
291     private RefactoringStatus checkSelection(CompilationUnitRewrite cuRewrite, IProgressMonitor pm) {
292         if (fSelectedExpression == null){
293             String JavaDoc message= RefactoringCoreMessages.IntroduceParameterRefactoring_select;
294             return CodeRefactoringUtil.checkMethodSyntaxErrors(fSelectionStart, fSelectionLength, cuRewrite.getRoot(), message);
295         }
296         
297         MethodDeclaration methodDeclaration= (MethodDeclaration) ASTNodes.getParent(fSelectedExpression, MethodDeclaration.class);
298         if (methodDeclaration == null)
299             return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_in_method);
300         if (methodDeclaration.resolveBinding() == null)
301             return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_no_binding);
302         //TODO: check for rippleMethods -> find matching fragments, consider callers of all rippleMethods
303

304         RefactoringStatus result= new RefactoringStatus();
305         result.merge(checkExpression());
306         if (result.hasFatalError())
307             return result;
308         
309         result.merge(checkExpressionBinding());
310         if (result.hasFatalError())
311             return result;
312         
313 // if (isUsedInForInitializerOrUpdater(getSelectedExpression().getAssociatedExpression()))
314
// return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("ExtractTempRefactoring.for_initializer_updater")); //$NON-NLS-1$
315
// pm.worked(1);
316
//
317
// if (isReferringToLocalVariableFromFor(getSelectedExpression().getAssociatedExpression()))
318
// return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("ExtractTempRefactoring.refers_to_for_variable")); //$NON-NLS-1$
319
// pm.worked(1);
320

321         return result;
322     }
323
324     private RefactoringStatus checkExpression() {
325         //TODO: adjust error messages (or generalize for all refactorings on expression-selections?)
326
Expression selectedExpression= fSelectedExpression;
327         
328         if (selectedExpression instanceof Name && selectedExpression.getParent() instanceof ClassInstanceCreation)
329             return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_name_in_new);
330             //TODO: let's just take the CIC automatically (no ambiguity -> no problem -> no dialog ;-)
331

332         if (selectedExpression instanceof NullLiteral) {
333             return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals);
334         } else if (selectedExpression instanceof ArrayInitializer) {
335             return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer);
336         } else if (selectedExpression instanceof Assignment) {
337             if (selectedExpression.getParent() instanceof Expression)
338                 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment);
339             else
340                 return null;
341
342         } else if (selectedExpression instanceof SimpleName){
343             if ((((SimpleName)selectedExpression)).isDeclaration())
344                 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations);
345             if (selectedExpression.getParent() instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
346                     || selectedExpression.getParent() instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
347                 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression);
348         }
349         
350         return null;
351     }
352
353     private RefactoringStatus checkExpressionBinding() {
354         return checkExpressionFragmentIsRValue();
355     }
356     
357     // !! +/- same as in ExtractConstantRefactoring & ExtractTempRefactoring
358
private RefactoringStatus checkExpressionFragmentIsRValue() {
359         switch(Checks.checkExpressionIsRValue(fSelectedExpression)) {
360             case Checks.NOT_RVALUE_MISC:
361                 return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.IntroduceParameterRefactoring_select, null, Corext.getPluginId(), RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, null);
362             case Checks.NOT_RVALUE_VOID:
363                 return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.IntroduceParameterRefactoring_no_void, null, Corext.getPluginId(), RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID, null);
364             case Checks.IS_RVALUE:
365                 return new RefactoringStatus();
366             default:
367                 Assert.isTrue(false); return null;
368         }
369     }
370
371     public List JavaDoc getParameterInfos() {
372         return fChangeSignatureRefactoring.getParameterInfos();
373     }
374     
375     public ParameterInfo getAddedParameterInfo() {
376         return fParameter;
377     }
378     
379     public String JavaDoc getMethodSignaturePreview() throws JavaModelException {
380         return fChangeSignatureRefactoring.getNewMethodSignature();
381     }
382     
383 //--- Input setting/validation
384

385     public void setParameterName(String JavaDoc name) {
386         Assert.isNotNull(name);
387         fParameter.setNewName(name);
388     }
389     
390     /**
391      * must only be called <i>after</i> checkActivation()
392      * @return guessed parameter name
393      */

394     public String JavaDoc guessedParameterName() {
395         String JavaDoc[] proposals= guessParameterNames();
396         if (proposals.length == 0)
397             return ""; //$NON-NLS-1$
398
else
399             return proposals[0];
400     }
401     
402 // --- TODO: copied from ExtractTempRefactoring - should extract ------------------------------
403

404     /**
405      * Must only be called <i>after</i> checkActivation().
406      * The first proposal should be used as "best guess" (if it exists).
407      * @return proposed variable names (may be empty, but not null).
408      */

409     public String JavaDoc[] guessParameterNames() {
410         LinkedHashSet JavaDoc proposals= new LinkedHashSet JavaDoc(); //retain ordering, but prevent duplicates
411
if (fSelectedExpression instanceof MethodInvocation){
412             proposals.addAll(guessTempNamesFromMethodInvocation((MethodInvocation) fSelectedExpression, fExcludedParameterNames));
413         }
414         proposals.addAll(guessTempNamesFromExpression(fSelectedExpression, fExcludedParameterNames));
415         return (String JavaDoc[]) proposals.toArray(new String JavaDoc[proposals.size()]);
416     }
417     
418     private List JavaDoc/*<String>*/ guessTempNamesFromMethodInvocation(MethodInvocation selectedMethodInvocation, String JavaDoc[] excludedVariableNames) {
419         String JavaDoc methodName= selectedMethodInvocation.getName().getIdentifier();
420         for (int i= 0; i < KNOWN_METHOD_NAME_PREFIXES.length; i++) {
421             String JavaDoc prefix= KNOWN_METHOD_NAME_PREFIXES[i];
422             if (! methodName.startsWith(prefix))
423                 continue; //not this prefix
424
if (methodName.length() == prefix.length())
425                 return Collections.EMPTY_LIST; // prefix alone -> don't take method name
426
char firstAfterPrefix= methodName.charAt(prefix.length());
427             if (! Character.isUpperCase(firstAfterPrefix))
428                 continue; //not uppercase after prefix
429
//found matching prefix
430
String JavaDoc proposal= Character.toLowerCase(firstAfterPrefix) + methodName.substring(prefix.length() + 1);
431             methodName= proposal;
432             break;
433         }
434         String JavaDoc[] proposals= StubUtility.getLocalNameSuggestions(fSourceCU.getJavaProject(), methodName, 0, excludedVariableNames);
435         return Arrays.asList(proposals);
436     }
437     
438     private List JavaDoc/*<String>*/ guessTempNamesFromExpression(Expression selectedExpression, String JavaDoc[] excluded) {
439         ITypeBinding expressionBinding= Bindings.normalizeForDeclarationUse(
440             selectedExpression.resolveTypeBinding(),
441             selectedExpression.getAST());
442         String JavaDoc typeName= getQualifiedName(expressionBinding);
443         if (typeName.length() == 0)
444             typeName= expressionBinding.getName();
445         if (typeName.length() == 0)
446             return Collections.EMPTY_LIST;
447         int typeParamStart= typeName.indexOf("<"); //$NON-NLS-1$
448
if (typeParamStart != -1)
449             typeName= typeName.substring(0, typeParamStart);
450         String JavaDoc[] proposals= StubUtility.getLocalNameSuggestions(fSourceCU.getJavaProject(), typeName, expressionBinding.getDimensions(), excluded);
451         return Arrays.asList(proposals);
452     }
453     
454 // ----------------------------------------------------------------------
455

456     private static String JavaDoc getQualifiedName(ITypeBinding typeBinding) {
457         if (typeBinding.isAnonymous())
458             return getQualifiedName(typeBinding.getSuperclass());
459         if (! typeBinding.isArray())
460             return typeBinding.getQualifiedName();
461         else
462             return typeBinding.getElementType().getQualifiedName();
463     }
464
465     private void initializeExcludedParameterNames(CompilationUnitRewrite cuRewrite) {
466         IBinding[] bindings= new ScopeAnalyzer(cuRewrite.getRoot()).getDeclarationsInScope(
467                 fSelectedExpression.getStartPosition(), ScopeAnalyzer.VARIABLES);
468         fExcludedParameterNames= new String JavaDoc[bindings.length];
469         for (int i= 0; i < fExcludedParameterNames.length; i++) {
470             fExcludedParameterNames[i]= bindings[i].getName();
471         }
472     }
473     
474     public RefactoringStatus validateInput() {
475         return fChangeSignatureRefactoring.checkSignature();
476     }
477     
478 //--- checkInput
479

480     public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
481         fChangeSignatureRefactoring.setValidationContext(getValidationContext());
482         RefactoringStatus result;
483         try {
484             result= fChangeSignatureRefactoring.checkFinalConditions(pm);
485         } finally {
486             fChangeSignatureRefactoring.setValidationContext(null);
487         }
488         return result;
489     }
490     
491     public Change createChange(IProgressMonitor pm) throws CoreException {
492         fChangeSignatureRefactoring.setValidationContext(getValidationContext());
493         Change result;
494         try {
495             result= fChangeSignatureRefactoring.createChange(pm);
496         } finally {
497             fChangeSignatureRefactoring.setValidationContext(null);
498         }
499         if (result != null) {
500             final ChangeDescriptor descriptor= result.getDescriptor();
501             if (descriptor instanceof RefactoringChangeDescriptor) {
502                 final RefactoringDescriptor refactoringDescriptor= ((RefactoringChangeDescriptor) descriptor).getRefactoringDescriptor();
503                 if (refactoringDescriptor instanceof JDTRefactoringDescriptor) {
504                     final JDTRefactoringDescriptor extended= (JDTRefactoringDescriptor) refactoringDescriptor;
505                     final Map JavaDoc arguments= new HashMap JavaDoc();
506                     arguments.put(ATTRIBUTE_ARGUMENT, fParameter.getNewName());
507                     arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer JavaDoc(fSelectionStart).toString() + " " + new Integer JavaDoc(fSelectionLength).toString()); //$NON-NLS-1$
508
arguments.putAll(extended.getArguments());
509                     String JavaDoc signature= fChangeSignatureRefactoring.getMethodName();
510                     try {
511                         signature= fChangeSignatureRefactoring.getOldMethodSignature();
512                     } catch (JavaModelException exception) {
513                         JavaPlugin.log(exception);
514                     }
515                     final String JavaDoc description= Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_descriptor_description_short, fChangeSignatureRefactoring.getMethod().getElementName());
516                     final String JavaDoc header= Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_descriptor_description, new String JavaDoc[] { fParameter.getNewName(), signature, ASTNodes.asString(fSelectedExpression)});
517                     final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(extended.getProject(), this, header);
518                     comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_original_pattern, JavaElementLabels.getTextLabel(fChangeSignatureRefactoring.getMethod(), JavaElementLabels.ALL_FULLY_QUALIFIED)));
519                     comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_pattern, ASTNodes.asString(fSelectedExpression)));
520                     comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_parameter_pattern, getAddedParameterInfo().getNewName()));
521                     result= new RefactoringDescriptorChange(new JDTRefactoringDescriptor(IJavaRefactorings.INTRODUCE_PARAMETER, extended.getProject(), description, comment.asString(), arguments, extended.getFlags()), RefactoringCoreMessages.IntroduceParameterRefactoring_name, new Change[] { result});
522                 }
523             }
524         }
525         return result;
526     }
527
528     public RefactoringStatus initialize(final RefactoringArguments arguments) {
529         fArguments= arguments;
530         if (arguments instanceof JavaRefactoringArguments) {
531             final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
532             final String JavaDoc selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
533             if (selection != null) {
534                 int offset= -1;
535                 int length= -1;
536                 final StringTokenizer JavaDoc tokenizer= new StringTokenizer JavaDoc(selection);
537                 if (tokenizer.hasMoreTokens())
538                     offset= Integer.valueOf(tokenizer.nextToken()).intValue();
539                 if (tokenizer.hasMoreTokens())
540                     length= Integer.valueOf(tokenizer.nextToken()).intValue();
541                 if (offset >= 0 && length >= 0) {
542                     fSelectionStart= offset;
543                     fSelectionLength= length;
544                 } else
545                     return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object JavaDoc[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
546             } else
547                 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
548             final String JavaDoc handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
549             if (handle != null) {
550                 final IJavaElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
551                 if (element == null || !element.exists() || element.getElementType() != IJavaElement.COMPILATION_UNIT)
552                     return createInputFatalStatus(element, IJavaRefactorings.INTRODUCE_PARAMETER);
553                 else
554                     fSourceCU= ((IMethod) element).getCompilationUnit();
555             } else
556                 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
557             final String JavaDoc name= extended.getAttribute(ATTRIBUTE_ARGUMENT);
558             if (name != null && !"".equals(name)) //$NON-NLS-1$
559
fParameterName= name;
560             else
561                 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ARGUMENT));
562         } else
563             return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
564         return new RefactoringStatus();
565     }
566
567     /**
568      * {@inheritDoc}
569      */

570     public String JavaDoc getDelegateUpdatingTitle(boolean plural) {
571         if (plural)
572             return RefactoringCoreMessages.DelegateCreator_keep_original_changed_plural;
573         else
574             return RefactoringCoreMessages.DelegateCreator_keep_original_changed_singular;
575     }
576 }
577
Popular Tags