Java Code Examples for org.eclipse.jdt.core.refactoring.CompilationUnitChange#addTextEditGroup()
The following examples show how to use
org.eclipse.jdt.core.refactoring.CompilationUnitChange#addTextEditGroup() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 6 votes |
private void createStateField() { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); AST contextAST = sourceTypeDeclaration.getAST(); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST); FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment); sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null); ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null); contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null); try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } }
Example 2
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 6 votes |
private void initializeReturnedVariableDeclaration() { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); AST contextAST = sourceTypeDeclaration.getAST(); if(returnedVariable != null) { IVariableBinding returnedVariableBinding = returnedVariable.resolveBinding(); if(returnedVariable instanceof VariableDeclarationFragment && !returnedVariableBinding.isField()) { VariableDeclarationFragment variableDeclarationFragment = (VariableDeclarationFragment)returnedVariable; if(variableDeclarationFragment.getInitializer() == null) { Expression defaultValue = generateDefaultValue(sourceRewriter, contextAST, returnedVariableBinding.getType()); sourceRewriter.set(variableDeclarationFragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, defaultValue, null); } } } try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Initialize returned variable", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } }
Example 3
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 6 votes |
private void addRequiredImportDeclarationsToContext() { ImportRewrite sourceImportRewrite = ImportRewrite.create(sourceCompilationUnit, true); for(ITypeBinding typeBinding : requiredImportDeclarationsForContext) { if(!typeBinding.isNested()) sourceImportRewrite.addImport(typeBinding); } try { TextEdit sourceImportEdit = sourceImportRewrite.rewriteImports(null); if(sourceImportRewrite.getCreatedImports().length > 0) { ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceImportEdit); change.addTextEditGroup(new TextEditGroup("Add required import declarations", new TextEdit[] {sourceImportEdit})); } } catch (CoreException e) { e.printStackTrace(); } }
Example 4
Source File: RenameLocalVariableProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private void createEdits() { TextEdit declarationEdit= createRenameEdit(fTempDeclarationNode.getName().getStartPosition()); TextEdit[] allRenameEdits= getAllRenameEdits(declarationEdit); TextEdit[] allUnparentedRenameEdits= new TextEdit[allRenameEdits.length]; TextEdit unparentedDeclarationEdit= null; fChange= new CompilationUnitChange(RefactoringCoreMessages.RenameTempRefactoring_rename, fCu); MultiTextEdit rootEdit= new MultiTextEdit(); fChange.setEdit(rootEdit); fChange.setKeepPreviewEdits(true); for (int i= 0; i < allRenameEdits.length; i++) { if (fIsComposite) { // Add a copy of the text edit (text edit may only have one // parent) to keep problem reporting code clean TextChangeCompatibility.addTextEdit(fChangeManager.get(fCu), RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i].copy(), fCategorySet); // Add a separate copy for problem reporting allUnparentedRenameEdits[i]= allRenameEdits[i].copy(); if (allRenameEdits[i].equals(declarationEdit)) { unparentedDeclarationEdit= allUnparentedRenameEdits[i]; } } rootEdit.addChild(allRenameEdits[i]); fChange.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i])); } // store information for analysis if (fIsComposite) { fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(unparentedDeclarationEdit, allUnparentedRenameEdits); } else { fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(declarationEdit, allRenameEdits); } }
Example 5
Source File: ExtractMethodRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private void replaceDuplicates(CompilationUnitChange result, int modifiers) { int numberOf = getNumberOfDuplicates(); if (numberOf == 0 || !fReplaceDuplicates) { return; } String label = null; if (numberOf == 1) { label = Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_single, BasicElementLabels.getJavaElementName(fMethodName)); } else { label = Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_multi, BasicElementLabels.getJavaElementName(fMethodName)); } TextEditGroup description = new TextEditGroup(label); result.addTextEditGroup(description); for (Match duplicate : fDuplicates) { if (!duplicate.isInvalidNode()) { if (isDestinationReachable(duplicate.getEnclosingMethod())) { ASTNode[] callNodes = createCallNodes(duplicate, modifiers); ASTNode[] duplicateNodes = duplicate.getNodes(); for (int i = 0; i < duplicateNodes.length; i++) { ASTNode parent = duplicateNodes[i].getParent(); if (parent instanceof ParenthesizedExpression) { duplicateNodes[i] = parent; } } new StatementRewrite(fRewriter, duplicateNodes).replace(callNodes, description); } } } }
Example 6
Source File: ChangeTypeRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void updateType(CompilationUnit cu, Type oldType, CompilationUnitChange unitChange, ASTRewrite unitRewriter, String typeName) { String oldName= fSelectionTypeBinding.getName(); String[] keys= { BasicElementLabels.getJavaElementName(oldName), BasicElementLabels.getJavaElementName(typeName)}; String description= Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_typeChange, keys); TextEditGroup gd= new TextEditGroup(description); AST ast= cu.getAST(); ASTNode nodeToReplace= oldType; if (fSelectionTypeBinding.isParameterizedType() && !fSelectionTypeBinding.isRawType()){ if (oldType.isSimpleType()){ nodeToReplace= oldType.getParent(); } } //TODO handle types other than simple & parameterized (e.g., arrays) Assert.isTrue(fSelectedType.isClass() || fSelectedType.isInterface()); Type newType= null; if (!fSelectedType.isParameterizedType()){ newType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeName)); } else { newType= createParameterizedType(ast, fSelectedType); } unitRewriter.replace(nodeToReplace, newType, gd); unitChange.addTextEditGroup(gd); }
Example 7
Source File: RenameLocalVariableProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void createEdits() { TextEdit declarationEdit= createRenameEdit(fTempDeclarationNode.getName().getStartPosition()); TextEdit[] allRenameEdits= getAllRenameEdits(declarationEdit); TextEdit[] allUnparentedRenameEdits= new TextEdit[allRenameEdits.length]; TextEdit unparentedDeclarationEdit= null; fChange= new CompilationUnitChange(RefactoringCoreMessages.RenameTempRefactoring_rename, fCu); MultiTextEdit rootEdit= new MultiTextEdit(); fChange.setEdit(rootEdit); fChange.setKeepPreviewEdits(true); for (int i= 0; i < allRenameEdits.length; i++) { if (fIsComposite) { // Add a copy of the text edit (text edit may only have one // parent) to keep problem reporting code clean TextChangeCompatibility.addTextEdit(fChangeManager.get(fCu), RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i].copy(), fCategorySet); // Add a separate copy for problem reporting allUnparentedRenameEdits[i]= allRenameEdits[i].copy(); if (allRenameEdits[i].equals(declarationEdit)) unparentedDeclarationEdit= allUnparentedRenameEdits[i]; } rootEdit.addChild(allRenameEdits[i]); fChange.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i])); } // store information for analysis if (fIsComposite) { fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(unparentedDeclarationEdit, allUnparentedRenameEdits); } else fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(declarationEdit, allRenameEdits); }
Example 8
Source File: ExtractMethodRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void replaceDuplicates(CompilationUnitChange result, int modifiers) { int numberOf= getNumberOfDuplicates(); if (numberOf == 0 || !fReplaceDuplicates) return; String label= null; if (numberOf == 1) label= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_single, BasicElementLabels.getJavaElementName(fMethodName)); else label= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_multi, BasicElementLabels.getJavaElementName(fMethodName)); TextEditGroup description= new TextEditGroup(label); result.addTextEditGroup(description); for (int d= 0; d < fDuplicates.length; d++) { SnippetFinder.Match duplicate= fDuplicates[d]; if (!duplicate.isInvalidNode()) { if (isDestinationReachable(duplicate.getEnclosingMethod())) { ASTNode[] callNodes= createCallNodes(duplicate, modifiers); ASTNode[] duplicateNodes= duplicate.getNodes(); for (int i= 0; i < duplicateNodes.length; i++) { ASTNode parent= duplicateNodes[i].getParent(); if (parent instanceof ParenthesizedExpression) { duplicateNodes[i]= parent; } } new StatementRewrite(fRewriter, duplicateNodes).replace(callNodes, description); } } } }
Example 9
Source File: TextEditFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * {@inheritDoc} */ public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException { String label= fChangeDescription; CompilationUnitChange result= new CompilationUnitChange(label, fUnit); result.setEdit(fEdit); result.addTextEditGroup(new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label)))); return result; }
Example 10
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 5 votes |
private void replacePrimitiveStateField() { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); AST contextAST = sourceTypeDeclaration.getAST(); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); FieldDeclaration[] fieldDeclarations = sourceTypeDeclaration.getFields(); for(FieldDeclaration fieldDeclaration : fieldDeclarations) { List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for(VariableDeclarationFragment fragment : fragments) { if(fragment.equals(typeCheckElimination.getTypeField())) { if(fragments.size() == 1) { ListRewrite fragmentsRewriter = sourceRewriter.getListRewrite(fieldDeclaration, FieldDeclaration.FRAGMENTS_PROPERTY); fragmentsRewriter.remove(fragment, null); VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST); fragmentsRewriter.insertLast(typeFragment, null); sourceRewriter.set(fieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null); } } } } try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Replace primitive type with State type", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } }
Example 11
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 5 votes |
private void removePrimitiveStateField() { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); AST contextAST = sourceTypeDeclaration.getAST(); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); FieldDeclaration[] fieldDeclarations = sourceTypeDeclaration.getFields(); for(FieldDeclaration fieldDeclaration : fieldDeclarations) { List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for(VariableDeclarationFragment fragment : fragments) { if(fragment.equals(typeCheckElimination.getTypeField())) { if(fragments.size() == 1) { contextBodyRewrite.remove(fragment.getParent(), null); } else { ListRewrite fragmentRewrite = sourceRewriter.getListRewrite(fragment.getParent(), FieldDeclaration.FRAGMENTS_PROPERTY); fragmentRewrite.remove(fragment, null); } } } } try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Remove primitive field holding the current state", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } }
Example 12
Source File: InlineMethodRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask("", 20); //$NON-NLS-1$ fChangeManager= new TextChangeManager(); RefactoringStatus result= new RefactoringStatus(); fSourceProvider.initialize(); fTargetProvider.initialize(); pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching); RefactoringStatus searchStatus= new RefactoringStatus(); String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName())); ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription); ICompilationUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1)); binaryRefs.addErrorIfNecessary(searchStatus); if (searchStatus.hasFatalError()) { result.merge(searchStatus); return result; } IFile[] filesToBeModified= getFilesToBeModified(units); result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext())); if (result.hasFatalError()) return result; result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1))); checkOverridden(result, new SubProgressMonitor(pm, 4)); IProgressMonitor sub= new SubProgressMonitor(pm, 15); sub.beginTask("", units.length * 3); //$NON-NLS-1$ for (int c= 0; c < units.length; c++) { ICompilationUnit unit= units[c]; sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit))); CallInliner inliner= null; try { boolean added= false; MultiTextEdit root= new MultiTextEdit(); CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit); change.setEdit(root); BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1)); if (bodies.length == 0) continue; inliner= new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider); for (int b= 0; b < bodies.length; b++) { BodyDeclaration body= bodies[b]; inliner.initialize(body); RefactoringStatus nestedInvocations= new RefactoringStatus(); ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2))); for (int i= 0; i < invocations.length; i++) { ASTNode invocation= invocations[i]; result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity())); if (result.hasFatalError()) break; if (result.getSeverity() < fTargetProvider.getStatusSeverity()) { added= true; TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline); change.addTextEditGroup(group); result.merge(inliner.perform(group)); } else { fDeleteSource= false; } } // do this after we have inlined the method calls. We still want // to generate the modifications. if (!nestedInvocations.isOK()) { result.merge(nestedInvocations); fDeleteSource= false; } } if (!added) { fChangeManager.remove(unit); } else { root.addChild(inliner.getModifications()); ImportRewrite rewrite= inliner.getImportEdit(); if (rewrite.hasRecordedChanges()) { TextEdit edit= rewrite.rewriteImports(null); if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) { root.addChild(edit); change.addTextEditGroup( new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit})); } } } } finally { if (inliner != null) inliner.dispose(); } sub.worked(1); if (sub.isCanceled()) throw new OperationCanceledException(); } result.merge(searchStatus); sub.done(); pm.done(); return result; }
Example 13
Source File: ReplaceInvocationsRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask("", 20); //$NON-NLS-1$ fChangeManager= new TextChangeManager(); RefactoringStatus result= new RefactoringStatus(); fSourceProvider= resolveSourceProvider(fMethodBinding, result); if (result.hasFatalError()) return result; result.merge(fSourceProvider.checkActivation()); if (result.hasFatalError()) return result; fSourceProvider.initialize(); fTargetProvider.initialize(); pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching); RefactoringStatus searchStatus= new RefactoringStatus(); String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName())); ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription); ICompilationUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1)); binaryRefs.addErrorIfNecessary(searchStatus); if (searchStatus.hasFatalError()) { result.merge(searchStatus); return result; } IFile[] filesToBeModified= getFilesToBeModified(units); result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext())); if (result.hasFatalError()) return result; result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1))); checkOverridden(result, new SubProgressMonitor(pm, 4)); IProgressMonitor sub= new SubProgressMonitor(pm, 15); sub.beginTask("", units.length * 3); //$NON-NLS-1$ for (int c= 0; c < units.length; c++) { ICompilationUnit unit= units[c]; sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit))); CallInliner inliner= null; try { boolean added= false; MultiTextEdit root= new MultiTextEdit(); CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit); change.setEdit(root); BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1)); if (bodies.length == 0) continue; inliner= new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider); for (int b= 0; b < bodies.length; b++) { BodyDeclaration body= bodies[b]; inliner.initialize(body); RefactoringStatus nestedInvocations= new RefactoringStatus(); ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2))); for (int i= 0; i < invocations.length; i++) { ASTNode invocation= invocations[i]; result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity())); if (result.hasFatalError()) break; if (result.getSeverity() < fTargetProvider.getStatusSeverity()) { added= true; TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline); change.addTextEditGroup(group); result.merge(inliner.perform(group)); } } // do this after we have inlined the method calls. We still want // to generate the modifications. result.merge(nestedInvocations); } if (!added) { fChangeManager.remove(unit); } else { root.addChild(inliner.getModifications()); ImportRewrite rewrite= inliner.getImportEdit(); if (rewrite.hasRecordedChanges()) { TextEdit edit= rewrite.rewriteImports(null); if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) { root.addChild(edit); change.addTextEditGroup( new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit})); } } } } finally { if (inliner != null) inliner.dispose(); } sub.worked(1); if (sub.isCanceled()) throw new OperationCanceledException(); } result.merge(searchStatus); sub.done(); pm.done(); return result; }
Example 14
Source File: IntroduceFactoryRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
/** * Add all changes necessary on the <code>ICompilationUnit</code> in the given * <code>SearchResultGroup</code> to implement the refactoring transformation * to the given <code>CompilationUnitChange</code>. * @param rg the <code>SearchResultGroup</code> for which changes should be created * @param unitHandle * @param unitChange the CompilationUnitChange object for the compilation unit in question * @return <code>true</code> iff a change has been added * @throws CoreException */ private boolean addAllChangesFor(SearchResultGroup rg, ICompilationUnit unitHandle, CompilationUnitChange unitChange) throws CoreException { // ICompilationUnit unitHandle= rg.getCompilationUnit(); Assert.isTrue(rg == null || rg.getCompilationUnit() == unitHandle); CompilationUnit unit= getASTFor(unitHandle); ASTRewrite unitRewriter= ASTRewrite.create(unit.getAST()); MultiTextEdit root= new MultiTextEdit(); boolean someChange= false; unitChange.setEdit(root); fImportRewriter= StubUtility.createImportRewrite(unit, true); // First create the factory method if (unitHandle.equals(fFactoryUnitHandle)) { TextEditGroup factoryGD= new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_addFactoryMethod); createFactoryChange(unitRewriter, unit, factoryGD); unitChange.addTextEditGroup(factoryGD); someChange= true; } // Now rewrite all the constructor calls to use the factory method if (rg != null) if (replaceConstructorCalls(rg, unit, unitRewriter, unitChange)) someChange= true; // Finally, make the constructor private, if requested. if (shouldProtectConstructor() && isConstructorUnit(unitHandle)) { TextEditGroup declGD= new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_protectConstructor); if (protectConstructor(unit, unitRewriter, declGD)) { unitChange.addTextEditGroup(declGD); someChange= true; } } if (someChange) { root.addChild(unitRewriter.rewriteAST()); root.addChild(fImportRewriter.rewriteImports(null)); } return someChange; }
Example 15
Source File: PolymorphismRefactoring.java From JDeodorant with MIT License | 4 votes |
protected void generateGettersForAccessedFields() { AST contextAST = sourceTypeDeclaration.getAST(); Set<VariableDeclarationFragment> accessedFields = new LinkedHashSet<VariableDeclarationFragment>(); accessedFields.addAll(typeCheckElimination.getAccessedFields()); accessedFields.addAll(typeCheckElimination.getSuperAccessedFields()); for(VariableDeclarationFragment fragment : accessedFields) { if((fragment.resolveBinding().getModifiers() & Modifier.STATIC) == 0) { IMethodBinding getterMethodBinding = null; if(typeCheckElimination.getSuperAccessedFields().contains(fragment)) { for(IVariableBinding fieldBinding : typeCheckElimination.getSuperAccessedFieldBindings()) { if(fieldBinding.isEqualTo(fragment.resolveBinding())) { getterMethodBinding = typeCheckElimination.getGetterMethodBindingOfSuperAccessedField(fieldBinding); break; } } } else { getterMethodBinding = findGetterMethodInContext(fragment.resolveBinding()); } if(getterMethodBinding == null) { FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent(); int modifiers = fieldDeclaration.getModifiers(); if(!fragment.equals(typeCheckElimination.getTypeField()) && !((modifiers & Modifier.PUBLIC) != 0 && (modifiers & Modifier.STATIC) != 0)) { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); MethodDeclaration newMethodDeclaration = contextAST.newMethodDeclaration(); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, fieldDeclaration.getType(), null); ListRewrite methodDeclarationModifiersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY); methodDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD), null); String methodName = fragment.getName().getIdentifier(); methodName = "get" + methodName.substring(0,1).toUpperCase() + methodName.substring(1,methodName.length()); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.NAME_PROPERTY, contextAST.newSimpleName(methodName), null); Block methodDeclarationBody = contextAST.newBlock(); ListRewrite methodDeclarationBodyStatementsRewrite = sourceRewriter.getListRewrite(methodDeclarationBody, Block.STATEMENTS_PROPERTY); ReturnStatement returnStatement = contextAST.newReturnStatement(); sourceRewriter.set(returnStatement, ReturnStatement.EXPRESSION_PROPERTY, fragment.getName(), null); methodDeclarationBodyStatementsRewrite.insertLast(returnStatement, null); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.BODY_PROPERTY, methodDeclarationBody, null); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); contextBodyRewrite.insertLast(newMethodDeclaration, null); try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Create getter method for accessed field", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } } } } } }
Example 16
Source File: PolymorphismRefactoring.java From JDeodorant with MIT License | 4 votes |
protected void generateSettersForAssignedFields() { AST contextAST = sourceTypeDeclaration.getAST(); Set<VariableDeclarationFragment> assignedFields = new LinkedHashSet<VariableDeclarationFragment>(); assignedFields.addAll(typeCheckElimination.getAssignedFields()); assignedFields.addAll(typeCheckElimination.getSuperAssignedFields()); for(VariableDeclarationFragment fragment : assignedFields) { IMethodBinding setterMethodBinding = null; if(typeCheckElimination.getSuperAssignedFields().contains(fragment)) { for(IVariableBinding fieldBinding : typeCheckElimination.getSuperAssignedFieldBindings()) { if(fieldBinding.isEqualTo(fragment.resolveBinding())) { setterMethodBinding = typeCheckElimination.getSetterMethodBindingOfSuperAssignedField(fieldBinding); break; } } } else { setterMethodBinding = findSetterMethodInContext(fragment.resolveBinding()); } if(setterMethodBinding == null) { FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent(); if(!fragment.equals(typeCheckElimination.getTypeField())) { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); MethodDeclaration newMethodDeclaration = contextAST.newMethodDeclaration(); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, contextAST.newPrimitiveType(PrimitiveType.VOID), null); ListRewrite methodDeclarationModifiersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY); methodDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD), null); String methodName = fragment.getName().getIdentifier(); methodName = "set" + methodName.substring(0,1).toUpperCase() + methodName.substring(1,methodName.length()); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.NAME_PROPERTY, contextAST.newSimpleName(methodName), null); ListRewrite methodDeclarationParametersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY); SingleVariableDeclaration parameter = contextAST.newSingleVariableDeclaration(); sourceRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldDeclaration.getType(), null); sourceRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, fragment.getName(), null); methodDeclarationParametersRewrite.insertLast(parameter, null); Block methodDeclarationBody = contextAST.newBlock(); ListRewrite methodDeclarationBodyStatementsRewrite = sourceRewriter.getListRewrite(methodDeclarationBody, Block.STATEMENTS_PROPERTY); Assignment assignment = contextAST.newAssignment(); sourceRewriter.set(assignment, Assignment.RIGHT_HAND_SIDE_PROPERTY, fragment.getName(), null); sourceRewriter.set(assignment, Assignment.OPERATOR_PROPERTY, Assignment.Operator.ASSIGN, null); FieldAccess fieldAccess = contextAST.newFieldAccess(); sourceRewriter.set(fieldAccess, FieldAccess.EXPRESSION_PROPERTY, contextAST.newThisExpression(), null); sourceRewriter.set(fieldAccess, FieldAccess.NAME_PROPERTY, fragment.getName(), null); sourceRewriter.set(assignment, Assignment.LEFT_HAND_SIDE_PROPERTY, fieldAccess, null); ExpressionStatement expressionStatement = contextAST.newExpressionStatement(assignment); methodDeclarationBodyStatementsRewrite.insertLast(expressionStatement, null); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.BODY_PROPERTY, methodDeclarationBody, null); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); contextBodyRewrite.insertLast(newMethodDeclaration, null); try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Create setter method for assigned field", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } } } } }