@Override public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException { CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite((ICompilationUnit)fCompilationUnit.getJavaElement(), fCompilationUnit); fLinkedProposalModel.clear(); for (int i= 0; i < fOperations.length; i++) { CompilationUnitRewriteOperation operation= fOperations[i]; operation.rewriteAST(cuRewrite, fLinkedProposalModel); } CompilationUnitChange result= cuRewrite.createChange(getDisplayString(), true, null); if (result == null) { throw new CoreException(new Status(IStatus.ERROR, JavaLanguageServerPlugin.PLUGIN_ID, Messages .format(FixMessages.CompilationUnitRewriteOperationsFix_nullChangeError, getDisplayString()))); } return result; }
/** {@inheritDoc} */ public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException { CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite( (ICompilationUnit) fCompilationUnit.getJavaElement(), fCompilationUnit); fLinkedProposalModel.clear(); for (int i = 0; i < fOperations.length; i++) { CompilationUnitRewriteOperation operation = fOperations[i]; operation.rewriteAST(cuRewrite, fLinkedProposalModel); } CompilationUnitChange result = cuRewrite.createChange(getDisplayString(), true, null); if (result == null) throw new CoreException( new Status( IStatus.ERROR, JavaPlugin.ID_PLUGIN, Messages.format( FixMessages.CompilationUnitRewriteOperationsFix_nullChangeError, getDisplayString()))); return result; }
static CompilationUnitChange createAddImportChange( ICompilationUnit cu, Name name, String fullyQualifiedName) throws CoreException { String[] args = { BasicElementLabels.getJavaElementName(Signature.getSimpleName(fullyQualifiedName)), BasicElementLabels.getJavaElementName(Signature.getQualifier(fullyQualifiedName)) }; String label = Messages.format( CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, args); CompilationUnitChange cuChange = new CompilationUnitChange(label, cu); ImportRewrite importRewrite = StubUtility.createImportRewrite((CompilationUnit) name.getRoot(), true); importRewrite.addImport(fullyQualifiedName); cuChange.setEdit(importRewrite.rewriteImports(null)); return cuChange; }
/** * Destructively clones a {@link CompilationUnitChange} where the cloned * change will have a different compilation unit. This does not update text * regions or anything more than setting the change properties and moving text * edits from the old to new change. * * @param originalChange the original change, this change's internal state * will likely become invalid (its text edits will be moved to the * new change) * @param cu the compilation unit to be used for the new * {@link CompilationUnitChange} * @return the cloned {@link CompilationUnitChange} */ public static CompilationUnitChange cloneCompilationUnitChangeWithDifferentCu( TextFileChange originalChange, ICompilationUnit cu) { CompilationUnitChange newChange = new CompilationUnitChange( originalChange.getName(), cu); newChange.setEdit(originalChange.getEdit()); newChange.setEnabledShallow(originalChange.isEnabled()); newChange.setKeepPreviewEdits(originalChange.getKeepPreviewEdits()); newChange.setSaveMode(originalChange.getSaveMode()); newChange.setTextType(originalChange.getTextType()); // Copy the changes over TextEditUtilities.moveTextEditGroupsIntoChange( originalChange.getChangeGroups(), newChange); return newChange; }
private void updateCu(CompilationUnit unit, Set<ConstraintVariable> vars, CompilationUnitChange unitChange, ASTRewrite unitRewriter, String typeName) throws JavaModelException { // use custom SourceRangeComputer to avoid losing comments unitRewriter.setTargetSourceRangeComputer(new SourceRangeComputer()); for (Iterator<ConstraintVariable> it=vars.iterator(); it.hasNext(); ){ ConstraintVariable cv = it.next(); ASTNode decl= findDeclaration(unit, cv); if ((decl instanceof SimpleName || decl instanceof QualifiedName) && cv instanceof ExpressionVariable) { ASTNode gp= decl.getParent().getParent(); updateType(unit, getType(gp), unitChange, unitRewriter, typeName); // local variable or parameter } else if (decl instanceof MethodDeclaration || decl instanceof FieldDeclaration) { updateType(unit, getType(decl), unitChange, unitRewriter, typeName); // method return or field type } else if (decl instanceof ParameterizedType){ updateType(unit, getType(decl), unitChange, unitRewriter, typeName); } } }
public static Change addFields(ICompilationUnit cu, List<String> fields) throws CoreException { AccessorClassModifier sourceModification= new AccessorClassModifier(cu); String message= Messages.format(NLSMessages.AccessorClassModifier_add_fields_to_accessor, BasicElementLabels.getFileName(cu)); TextChange change= new CompilationUnitChange(message, cu); MultiTextEdit multiTextEdit= new MultiTextEdit(); change.setEdit(multiTextEdit); for (int i= 0; i < fields.size(); i++) { String field= fields.get(i); NLSSubstitution substitution= new NLSSubstitution(NLSSubstitution.EXTERNALIZED, field, null, null, null); sourceModification.addKey(substitution, change); } if (change.getChangeGroups().length == 0) return null; change.addEdit(sourceModification.getTextEdit()); return change; }
public static Change removeFields(ICompilationUnit cu, List<String> fields) throws CoreException { AccessorClassModifier sourceModification= new AccessorClassModifier(cu); String message= Messages.format(NLSMessages.AccessorClassModifier_remove_fields_from_accessor, BasicElementLabels.getFileName(cu)); TextChange change= new CompilationUnitChange(message, cu); MultiTextEdit multiTextEdit= new MultiTextEdit(); change.setEdit(multiTextEdit); for (int i= 0; i < fields.size(); i++) { String field= fields.get(i); NLSSubstitution substitution= new NLSSubstitution(NLSSubstitution.EXTERNALIZED, field, null, null, null); sourceModification.removeKey(substitution, change); } if (change.getChangeGroups().length == 0) return null; change.addEdit(sourceModification.getTextEdit()); return change; }
/** * {@inheritDoc} */ public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException { CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite((ICompilationUnit)fCompilationUnit.getJavaElement(), fCompilationUnit); fLinkedProposalModel.clear(); for (int i= 0; i < fOperations.length; i++) { CompilationUnitRewriteOperation operation= fOperations[i]; operation.rewriteAST(cuRewrite, fLinkedProposalModel); } CompilationUnitChange result= cuRewrite.createChange(getDisplayString(), true, null); if (result == null) throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, Messages.format(FixMessages.CompilationUnitRewriteOperationsFix_nullChangeError, getDisplayString()))); return result; }
@Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { CompositeChange changes = new CompositeChange("Rename method change"); for (ICompilationUnit unit : map.keySet()) { TextEdit newEdit = map.get(unit).getAstRewrite().rewriteAST(); TextChange existingChange = getTextChange(unit); if (existingChange == null) { CompilationUnitChange change = new CompilationUnitChange("change", unit); change.setEdit(newEdit); changes.add(change); } else { TextEdit existingEdit = existingChange.getEdit(); if (existingEdit.covers(newEdit)) { mergeEdits(existingEdit, newEdit); } else { existingEdit.addChild(newEdit); } } } return changes; }
/** * Adds copyright header to the compilation unit * * @param compilationUnit * compilation unit affected * @return compilation unit change */ public CompilationUnitChange addCopyrightsHeader(final CompilationUnit compilationUnit) { final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement(); change = new CompilationUnitChange(ADD_COPYRIGHT, unit); rewriter = ASTRewrite.create(compilationUnit.getAST()); final ListRewrite listRewrite = rewriter.getListRewrite(compilationUnit.getPackage(), PackageDeclaration.ANNOTATIONS_PROPERTY); final Comment placeHolder = (Comment) rewriter.createStringPlaceholder(getCopyrightText() + NEW_LINE_SEPARATOR, ASTNode.BLOCK_COMMENT); listRewrite.insertFirst(placeHolder, null); rewriteCompilationUnit(unit, getNewUnitSource(unit, null)); return change; }
/** * Replaces copyright header to the compilation unit * * @param compilationUnit * compilation unit affected * @return compilation unit change */ public CompilationUnitChange replaceCopyrightsHeader(final CompilationUnit compilationUnit) { final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement(); change = new CompilationUnitChange(OVERRIDE_COPYRIGHT, unit); rewriter = ASTRewrite.create(compilationUnit.getAST()); final List<Comment> comments = getCommentList(compilationUnit); Comment copyrightComment = null; if (!comments.isEmpty()) { copyrightComment = comments.get(0); } rewriteCompilationUnit(unit, getNewUnitSource(unit, copyrightComment)); return change; }
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); } } } }
@Override public Change createChange(IProgressMonitor pm) throws CoreException { final String NN = ""; //$NON-NLS-1$ if (pm == null) { pm = new NullProgressMonitor(); } pm.beginTask(NN, 2); try { final CompilationUnitChange result = new CompilationUnitChange(getName(), fCUnit); if (fLeaveDirty) { result.setSaveMode(TextFileChange.LEAVE_DIRTY); } MultiTextEdit root = new MultiTextEdit(); result.setEdit(root); fRewriter = ASTRewrite.create(fAnalyzer.getEnclosingBodyDeclaration().getAST()); fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(fAnalyzer.getSelectedNodes(), fCUnit.getBuffer(), fSelection.getOffset(), fSelection.getLength())); fImportRewrite = StubUtility.createImportRewrite(fRootNode, true); fLinkedProposalModel = new LinkedProposalModel(); fScope = CodeScopeBuilder.perform(fAnalyzer.getEnclosingBodyDeclaration(), fSelection).findScope(fSelection.getOffset(), fSelection.getLength()); fScope.setCursor(fSelection.getOffset()); fSelectedNodes = fAnalyzer.getSelectedNodes(); createTryCatchStatement(fCUnit.getBuffer(), fCUnit.findRecommendedLineSeparator()); if (fImportRewrite.hasRecordedChanges()) { TextEdit edit = fImportRewrite.rewriteImports(null); root.addChild(edit); result.addTextEditGroup(new TextEditGroup(NN, new TextEdit[] { edit })); } TextEdit change = fRewriter.rewriteAST(); root.addChild(change); result.addTextEditGroup(new TextEditGroup(NN, new TextEdit[] { change })); return result; } finally { pm.done(); } }
public static void addUnimplementedMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) { IProposableFix fix = UnimplementedCodeFix.createAddUnimplementedMethodsFix(context.getASTRoot(), problem); if (fix != null) { try { CompilationUnitChange change = fix.createChange(null); CUCorrectionProposal proposal = new CUCorrectionProposal(change.getName(), change.getCompilationUnit(), change, IProposalRelevance.ADD_UNIMPLEMENTED_METHODS); proposals.add(proposal); } catch (CoreException e) { JavaLanguageServerPlugin.log(e); } } }
public static void addUnusedMemberProposal(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) { int problemId = problem.getProblemId(); UnusedCodeFix fix = UnusedCodeFix.createUnusedMemberFix(context.getASTRoot(), problem, false); if (fix != null) { try { CompilationUnitChange change = fix.createChange(null); CUCorrectionProposal proposal = new CUCorrectionProposal(change.getName(), change.getCompilationUnit(), change, IProposalRelevance.UNUSED_MEMBER); proposals.add(proposal); } catch (CoreException e) { JavaLanguageServerPlugin.log(e); } } // TODO need to fork FixCorrectionProposal/ ICleanUp over from jdt.ui?? // if (problemId==IProblem.LocalVariableIsNeverUsed){ // fix= UnusedCodeFix.createUnusedMemberFix(context.getASTRoot(), problem, true); // addProposal(context, proposals, fix); // } if (problemId == IProblem.ArgumentIsNeverUsed) { JavadocTagsSubProcessor.getUnusedAndUndocumentedParameterOrExceptionProposals(context, problem, proposals); } if (problemId == IProblem.UnusedPrivateField) { GetterSetterCorrectionSubProcessor.addGetterSetterProposal(context, problem, proposals); } }
@Override protected TextChange createTextChange() throws CoreException { CompilationUnitChange createChange = fFix.createChange(null); createChange.setSaveMode(TextFileChange.LEAVE_DIRTY); // if (fFix instanceof ILinkedFix) { // setLinkedProposalModel(((ILinkedFix) fFix).getLinkedPositions()); // } return createChange; }
static CompilationUnitChange createAddImportChange(ICompilationUnit cu, Name name, String fullyQualifiedName) throws CoreException { String[] args= { BasicElementLabels.getJavaElementName(Signature.getSimpleName(fullyQualifiedName)), BasicElementLabels.getJavaElementName(Signature.getQualifier(fullyQualifiedName)) }; String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, args); CompilationUnitChange cuChange= new CompilationUnitChange(label, cu); ImportRewrite importRewrite= StubUtility.createImportRewrite((CompilationUnit) name.getRoot(), true); importRewrite.addImport(fullyQualifiedName); cuChange.setEdit(importRewrite.rewriteImports(null)); return cuChange; }
@Override public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException { final CompilationUnitChange change = new CompilationUnitChange("Remove unnecessary visibility modifiers", _context.getCompilationUnit()); final AST ast = _context.getAST().getAST(); final ASTRewrite rewriter = ASTRewrite.create(ast); for (final ASTNode node : _annotationsToRemove) { rewriter.remove(node, null); } addAnnotation(ast, rewriter, "ParametersAreNonnullByDefault", _nodesToAnnotateWithParameterAreNonnullByDefault); addAnnotation(ast, rewriter, "ReturnValuesAreNonnullByDefault", _nodesToAnnotateWithReturnValuesAreNonnullByDefault); change.setEdit(rewriter.rewriteAST()); final boolean addImportForParameters = !_nodesToAnnotateWithParameterAreNonnullByDefault.isEmpty(); final boolean addImportForReturns = !_nodesToAnnotateWithReturnValuesAreNonnullByDefault.isEmpty(); if (addImportForParameters || addImportForReturns) { final ImportRewrite importRewrite = createImportRewriterWithProjectSettings(); if (addImportForParameters) { importRewrite.addImport(Jsr305CleanUp.FQN_PARAMETERS_ARE_NONNULL_BY_DEFAULT); } if (addImportForReturns) { importRewrite.addImport(Jsr305CleanUp.FQN_RETURN_VALUES_ARE_NONNULL_BY_DEFAULT); } change.addEdit(importRewrite.rewriteImports(progressMonitor)); } return change; }
private void manageCompilationUnit(final TextEditBasedChangeManager manager, CompilationUnitRewrite rewrite, Optional<IProgressMonitor> monitor) throws CoreException { monitor.ifPresent(m -> m.beginTask("Creating change ...", IProgressMonitor.UNKNOWN)); CompilationUnitChange change = rewrite.createChange(false, monitor.orElseGet(NullProgressMonitor::new)); if (change != null) change.setTextType("java"); manager.manage(rewrite.getCu(), change); }
/** {@inheritDoc} */ public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException { if (fEditGroups == null || fEditGroups.length == 0) return null; CompilationUnitChange result = new CompilationUnitChange(getDisplayString(), fCompilationUnit); for (int i = 0; i < fEditGroups.length; i++) { TextEdit[] edits = fEditGroups[i].getTextEdits(); String groupName = fEditGroups[i].getName(); for (int j = 0; j < edits.length; j++) { TextChangeCompatibility.addTextEdit(result, groupName, edits[j]); } } return result; }
/** {@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; }
private void rewriteDeclarations(InferTypeArgumentsUpdate update, IProgressMonitor pm) throws CoreException { HashMap<ICompilationUnit, CuUpdate> updates = update.getUpdates(); Set<Entry<ICompilationUnit, CuUpdate>> entrySet = updates.entrySet(); pm.beginTask("", entrySet.size()); // $NON-NLS-1$ pm.setTaskName(RefactoringCoreMessages.InferTypeArgumentsRefactoring_creatingChanges); for (Iterator<Entry<ICompilationUnit, CuUpdate>> iter = entrySet.iterator(); iter.hasNext(); ) { if (pm.isCanceled()) throw new OperationCanceledException(); Entry<ICompilationUnit, CuUpdate> entry = iter.next(); ICompilationUnit cu = entry.getKey(); pm.worked(1); pm.subTask(BasicElementLabels.getFileName(cu)); CompilationUnitRewrite rewrite = new CompilationUnitRewrite(cu); rewrite.setResolveBindings(false); CuUpdate cuUpdate = entry.getValue(); for (Iterator<CollectionElementVariable2> cvIter = cuUpdate.getDeclarations().iterator(); cvIter.hasNext(); ) { ConstraintVariable2 cv = cvIter.next(); rewriteConstraintVariable(cv, rewrite, fTCModel, fLeaveUnconstrainedRaw, null); } for (Iterator<CastVariable2> castsIter = cuUpdate.getCastsToRemove().iterator(); castsIter.hasNext(); ) { CastVariable2 castCv = castsIter.next(); rewriteCastVariable(castCv, rewrite, fTCModel); } CompilationUnitChange change = rewrite.createChange(true); if (change != null) { fChangeManager.manage(cu, change); } } }
private void addDeclarationUpdate(TextChangeManager manager) throws CoreException { if (getDelegateUpdating()) { // create the delegate CompilationUnitRewrite rewrite = new CompilationUnitRewrite(getDeclaringCU()); rewrite.setResolveBindings(true); MethodDeclaration methodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(getMethod(), rewrite.getRoot()); DelegateMethodCreator creator = new DelegateMethodCreator(); creator.setDeclaration(methodDeclaration); creator.setDeclareDeprecated(getDeprecateDelegates()); creator.setSourceRewrite(rewrite); creator.setCopy(true); creator.setNewElementName(getNewElementName()); creator.prepareDelegate(); creator.createEdit(); CompilationUnitChange cuChange = rewrite.createChange(true); if (cuChange != null) { cuChange.setKeepPreviewEdits(true); manager.manage(getDeclaringCU(), cuChange); } } String editName = RefactoringCoreMessages.RenameMethodRefactoring_update_declaration; ISourceRange nameRange = getMethod().getNameRange(); ReplaceEdit replaceEdit = new ReplaceEdit(nameRange.getOffset(), nameRange.getLength(), getNewElementName()); addTextEdit(manager.get(getDeclaringCU()), editName, replaceEdit); }
public CompilationUnitChange createCompilationUnitChange(IProgressMonitor pm) throws CoreException { final CompilationUnitRewrite rewrite = new CompilationUnitRewrite(fCu, fCompilationUnitNode); final ITypeBinding[] typeParameters = getTypeParameters(); addNestedClass(rewrite, typeParameters); modifyConstructorCall(rewrite, typeParameters); return rewrite.createChange( RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_name, false, pm); }
@Override public Change createChange(IProgressMonitor pm) throws CoreException { pm.beginTask("", 1); // $NON-NLS-1$ try { if (fFieldName.length() == 0) { fFieldName = getInitialFieldName(); } ASTRewrite rewrite = ASTRewrite.create(fCompilationUnitNode.getAST()); if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer()) addLocalDeclarationSplit(rewrite); else addLocalDeclarationRemoval(rewrite); if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR) addInitializersToConstructors(rewrite); addTempRenames(rewrite); addFieldDeclaration(rewrite); CompilationUnitChange result = new CompilationUnitChange( RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu); result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor())); TextEdit resultingEdits = rewrite.rewriteAST(); TextChangeCompatibility.addTextEdit( result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits); return result; } finally { pm.done(); } }
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); } } } }
protected static CompilationUnitChange createCompilationUnitChange( CompilationUnitRewrite rewrite) throws CoreException { CompilationUnitChange change = rewrite.createChange(true); if (change != null) change.setSaveMode(TextFileChange.KEEP_SAVE_STATE); return change; }
@Override protected TextChange createTextChange() throws CoreException { CompilationUnitChange createChange = fFix.createChange(null); createChange.setSaveMode(TextFileChange.LEAVE_DIRTY); // if (fFix instanceof ILinkedFix) { // setLinkedProposalModel(((ILinkedFix)fFix).getLinkedPositions()); // } return createChange; }
public void run(IProgressMonitor monitor) throws CoreException { ICompilationUnit icu = clientBundle.getCompilationUnit(); CompilationUnit cu = JavaASTUtils.parseCompilationUnit(icu); ImportRewrite importRewrite = StubUtility.createImportRewrite(cu, true); // Find the target type declaration TypeDeclaration typeDecl = JavaASTUtils.findTypeDeclaration(cu, clientBundle.getFullyQualifiedName()); if (typeDecl == null) { throw new CoreException( StatusUtilities.newErrorStatus("Missing ClientBundle type " + clientBundle.getFullyQualifiedName(), GWTPlugin.PLUGIN_ID)); } // We need to rewrite the AST of the ClientBundle type declaration ASTRewrite astRewrite = ASTRewrite.create(cu.getAST()); ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(typeDecl); ListRewrite listRewriter = astRewrite.getListRewrite(typeDecl, property); // Add the new resource methods boolean addComments = StubUtility.doAddComments(icu.getJavaProject()); for (ClientBundleResource resource : resources) { listRewriter.insertLast(resource.createMethodDeclaration(clientBundle, astRewrite, importRewrite, addComments), null); } // Create the edit to add the methods and update the imports TextEdit rootEdit = new MultiTextEdit(); rootEdit.addChild(astRewrite.rewriteAST()); rootEdit.addChild(importRewrite.rewriteImports(null)); // Apply the change to the compilation unit CompilationUnitChange cuChange = new CompilationUnitChange( "Update ClientBundle", icu); cuChange.setSaveMode(TextFileChange.KEEP_SAVE_STATE); cuChange.setEdit(rootEdit); cuChange.perform(new NullProgressMonitor()); }
@Override public Change createPreChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { CompilationUnitChange change = new CompilationUnitChange(cu.getElementName(), cu); change.setKeepPreviewEdits(true); change.setEdit(new MultiTextEdit()); // parse javadocs and update references for (ImageReference reference : UmletPluginUtils.collectUxfImgRefs(cu)) { SourceString srcValue = reference.srcAttr.value; if (UmletPluginUtils.isAbsoluteImageRef(srcValue.getValue())) { continue; } IPackageFragment destinationPackage; { Object destination = getArguments().getDestination(); if (!(destination instanceof IPackageFragment)) { continue; } destinationPackage = (IPackageFragment) destination; } IPath parentPath = UmletPluginUtils.getCompilationUnitParentPath(cu); IPath imgPath = parentPath.append(new Path(srcValue.getValue())); IPath destinationPath = UmletPluginUtils.getPackageFragmentRootRelativePath(cu.getJavaProject(), destinationPackage.getCorrespondingResource()); String newPath = UmletPluginUtils.calculateImageRef(destinationPath, imgPath); change.addEdit(new ReplaceEdit(srcValue.start, srcValue.length(), newPath)); } return change; }
@Override public Change createChange(IProgressMonitor pm) throws CoreException { pm.beginTask(RefactoringCoreMessages.ChangeTypeMessages_CreateChangesForChangeType, 1); try { Map<ICompilationUnit, Set<ConstraintVariable>> relevantVarsByUnit= new HashMap<ICompilationUnit, Set<ConstraintVariable>>(); groupChangesByCompilationUnit(relevantVarsByUnit); final Map<String, String> arguments= new HashMap<String, String>(); String project= null; IJavaProject javaProject= fCu.getJavaProject(); if (javaProject != null) project= javaProject.getElementName(); final String description= RefactoringCoreMessages.ChangeTypeRefactoring_descriptor_description_short; final String header= Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(fSelectionBinding, JavaElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(fSelectedType, JavaElementLabels.ALL_FULLY_QUALIFIED)}); final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header); comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_original_element_pattern, BindingLabelProvider.getBindingLabel(fSelectionBinding, JavaElementLabels.ALL_FULLY_QUALIFIED))); comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_original_type_pattern, BindingLabelProvider.getBindingLabel(getOriginalType(), JavaElementLabels.ALL_FULLY_QUALIFIED))); comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_refactored_type_pattern, BindingLabelProvider.getBindingLabel(fSelectedType, JavaElementLabels.ALL_FULLY_QUALIFIED))); final GeneralizeTypeDescriptor descriptor= RefactoringSignatureDescriptorFactory.createGeneralizeTypeDescriptor(project, description, comment.asString(), arguments, (RefactoringDescriptor.STRUCTURAL_CHANGE | JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT)); arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu)); arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$ arguments.put(ATTRIBUTE_TYPE, fSelectedType.getQualifiedName()); final DynamicValidationRefactoringChange result= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ChangeTypeRefactoring_allChanges); for (Iterator<ICompilationUnit>it= relevantVarsByUnit.keySet().iterator(); it.hasNext();) { ICompilationUnit icu= it.next(); Set<ConstraintVariable> cVars= relevantVarsByUnit.get(icu); CompilationUnitChange cuChange= new CompilationUnitChange(getName(), icu); addAllChangesFor(icu, cVars, cuChange); result.add(cuChange); pm.worked(1); if (pm.isCanceled()) throw new OperationCanceledException(); } return result; } finally { pm.done(); } }
/** * Apply all changes related to a single ICompilationUnit * @param icu the compilation unit * @param vars * @param unitChange * @throws CoreException */ private void addAllChangesFor(ICompilationUnit icu, Set<ConstraintVariable> vars, CompilationUnitChange unitChange) throws CoreException { CompilationUnit unit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(icu, true); ASTRewrite unitRewriter= ASTRewrite.create(unit.getAST()); MultiTextEdit root= new MultiTextEdit(); unitChange.setEdit(root); // Adam sez don't need this, but then unitChange.addGroupDescription() fails an assertion! String typeName= updateImports(unit, root); updateCu(unit, vars, unitChange, unitRewriter, typeName); root.addChild(unitRewriter.rewriteAST()); }
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); }
protected void registerChanges(final TextEditBasedChangeManager manager) throws CoreException { ICompilationUnit unit= null; CompilationUnitRewrite rewrite= null; for (final Iterator<ICompilationUnit> iterator= fCompilationUnitRewrites.keySet().iterator(); iterator.hasNext();) { unit= iterator.next(); rewrite= fCompilationUnitRewrites.get(unit); if (rewrite != null) { final CompilationUnitChange change= rewrite.createChange(true); if (change != null) manager.manage(unit, change); } } }
private void rewriteDeclarations(InferTypeArgumentsUpdate update, IProgressMonitor pm) throws CoreException { HashMap<ICompilationUnit, CuUpdate> updates= update.getUpdates(); Set<Entry<ICompilationUnit, CuUpdate>> entrySet= updates.entrySet(); pm.beginTask("", entrySet.size()); //$NON-NLS-1$ pm.setTaskName(RefactoringCoreMessages.InferTypeArgumentsRefactoring_creatingChanges); for (Iterator<Entry<ICompilationUnit, CuUpdate>> iter= entrySet.iterator(); iter.hasNext();) { if (pm.isCanceled()) throw new OperationCanceledException(); Entry<ICompilationUnit, CuUpdate> entry= iter.next(); ICompilationUnit cu= entry.getKey(); pm.worked(1); pm.subTask(BasicElementLabels.getFileName(cu)); CompilationUnitRewrite rewrite= new CompilationUnitRewrite(cu); rewrite.setResolveBindings(false); CuUpdate cuUpdate= entry.getValue(); for (Iterator<CollectionElementVariable2> cvIter= cuUpdate.getDeclarations().iterator(); cvIter.hasNext();) { ConstraintVariable2 cv= cvIter.next(); rewriteConstraintVariable(cv, rewrite, fTCModel, fLeaveUnconstrainedRaw, null); } for (Iterator<CastVariable2> castsIter= cuUpdate.getCastsToRemove().iterator(); castsIter.hasNext();) { CastVariable2 castCv= castsIter.next(); rewriteCastVariable(castCv, rewrite, fTCModel); } CompilationUnitChange change= rewrite.createChange(true); if (change != null) { fChangeManager.manage(cu, change); } } }
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); }