List of usage examples for org.eclipse.jdt.core.dom.rewrite ListRewrite replace
public void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup)
From source file:com.github.parzonka.ccms.engine.SortElementsOperation.java
License:Open Source License
private ASTRewrite sortCompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit ast, final TextEditGroup group) { ast.accept(new ASTVisitor() { @Override/* w ww . j a va 2 s . c o m*/ public boolean visit(org.eclipse.jdt.core.dom.CompilationUnit compilationUnit) { final List<AbstractTypeDeclaration> types = compilationUnit.types(); for (final Iterator<AbstractTypeDeclaration> iter = types.iterator(); iter.hasNext();) { final AbstractTypeDeclaration typeDeclaration = iter.next(); typeDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(typeDeclaration.getStartPosition())); compilationUnit.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(typeDeclaration))); } return true; } @Override public boolean visit(AnnotationTypeDeclaration annotationTypeDeclaration) { final List bodyDeclarations = annotationTypeDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); annotationTypeDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) { final List bodyDeclarations = anonymousClassDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); anonymousClassDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(TypeDeclaration typeDeclaration) { final List bodyDeclarations = typeDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); typeDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(EnumDeclaration enumDeclaration) { final List bodyDeclarations = enumDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); enumDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } final List enumConstants = enumDeclaration.enumConstants(); for (final Iterator iter = enumConstants.iterator(); iter.hasNext();) { final EnumConstantDeclaration enumConstantDeclaration = (EnumConstantDeclaration) iter.next(); enumConstantDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(enumConstantDeclaration.getStartPosition())); enumDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(enumConstantDeclaration))); } return true; } }); final ASTRewrite rewriter = ASTRewrite.create(ast.getAST()); final boolean[] hasChanges = new boolean[] { false }; ast.accept(new ASTVisitor() { /** * This * * @param elements * @param listRewrite */ private void sortElements(List<BodyDeclaration> elements, ListRewrite listRewrite) { if (elements.size() == 0) return; final List<BodyDeclaration> myCopy = new ArrayList<BodyDeclaration>(); myCopy.addAll(elements); // orderexperiment final List<Signature> methods = new ArrayList<Signature>(); for (final BodyDeclaration bd : myCopy) { if (bd.getNodeType() == ASTNode.METHOD_DECLARATION) { methods.add(new Signature((MethodDeclaration) bd)); } } Collections.sort(methods, ((BodyDeclarationComparator) SortElementsOperation.this.comparator) .getMethodDeclarationComparator()); logger.info("Sorting of methods based on appearance:"); int j = 0; for (final Signature sig : methods) { logger.info("Method [{}] : {}", ++j, sig); } Collections.sort(myCopy, SortElementsOperation.this.comparator); logger.info("Final sorting order just before the AST-Rewrite:"); for (final BodyDeclaration bd : myCopy) { if (bd.getNodeType() == ASTNode.METHOD_DECLARATION) { logger.info("{}", new Signature((MethodDeclaration) bd)); } else { logger.info("{}", bd.toString()); } } for (int i = 0; i < elements.size(); i++) { final BodyDeclaration oldNode = elements.get(i); final BodyDeclaration newNode = myCopy.get(i); if (oldNode != newNode) { if (oldNode.getNodeType() == ASTNode.METHOD_DECLARATION && newNode.getNodeType() == ASTNode.METHOD_DECLARATION) { final Signature oldMethodSignature = new Signature((MethodDeclaration) oldNode); final Signature newMethodSignature = new Signature((MethodDeclaration) newNode); logger.trace("Swapping [{}]for [{}]", oldMethodSignature, newMethodSignature); } else { logger.trace("Swapping [{}]for [{}]", oldNode.getNodeType(), newNode.getNodeType()); } listRewrite.replace(oldNode, rewriter.createMoveTarget(newNode), group); hasChanges[0] = true; } } } @Override public boolean visit(org.eclipse.jdt.core.dom.CompilationUnit compilationUnit) { if (checkMalformedNodes(compilationUnit)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(compilationUnit.types(), rewriter.getListRewrite(compilationUnit, org.eclipse.jdt.core.dom.CompilationUnit.TYPES_PROPERTY)); return true; } @Override public boolean visit(AnnotationTypeDeclaration annotationTypeDeclaration) { if (checkMalformedNodes(annotationTypeDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(annotationTypeDeclaration.bodyDeclarations(), rewriter.getListRewrite( annotationTypeDeclaration, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) { if (checkMalformedNodes(anonymousClassDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(anonymousClassDeclaration.bodyDeclarations(), rewriter.getListRewrite( anonymousClassDeclaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(TypeDeclaration typeDeclaration) { if (checkMalformedNodes(typeDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(typeDeclaration.bodyDeclarations(), rewriter.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(EnumDeclaration enumDeclaration) { if (checkMalformedNodes(enumDeclaration)) { return true; // abort sorting of current element } sortElements(enumDeclaration.bodyDeclarations(), rewriter.getListRewrite(enumDeclaration, EnumDeclaration.BODY_DECLARATIONS_PROPERTY)); sortElements(enumDeclaration.enumConstants(), rewriter.getListRewrite(enumDeclaration, EnumDeclaration.ENUM_CONSTANTS_PROPERTY)); return true; } }); if (!hasChanges[0]) return null; return rewriter; }
From source file:com.halware.nakedide.eclipse.ext.annot.ast.AbstractAnnotationEvaluatorOrModifier.java
License:Open Source License
/** * Adds, updates or removes element for normal annotation, as required. * //from ww w. j a v a 2 s. c o m * @param normalAnnotation * @param newMemberValues * @param ast * @param rewrite */ private void maintainValuesProperty(NormalAnnotation normalAnnotation, Map<String, Object> newMemberValues, AST ast, ASTRewrite rewrite) { ListRewrite listRewrite = rewrite.getListRewrite(normalAnnotation, NormalAnnotation.VALUES_PROPERTY); LinkedHashMap<String, Object> existingMemberValues = ASTTools.memberValues(normalAnnotation); Set<String> existingKeySet = new HashSet<String>(existingMemberValues.keySet()); Set<String> newKeySet = new HashSet<String>(newMemberValues.keySet()); Set<String> commonMembers = new HashSet<String>(existingKeySet); commonMembers.retainAll(newKeySet); Set<String> newMembers = new HashSet<String>(newKeySet); newMembers.removeAll(existingKeySet); Set<String> removedMembers = new HashSet<String>(existingKeySet); removedMembers.removeAll(newKeySet); for (String memberName : commonMembers) { Object value = newMemberValues.get(memberName); MemberValuePair memberValuePair = ASTTools.memberValuePair(normalAnnotation, memberName); if (value != null) { MemberValuePair newValuePair = createMemberValuePair(ast, memberName, value); listRewrite.replace(memberValuePair, newValuePair, null); } else { listRewrite.remove(memberValuePair, null); } } for (String memberName : newMembers) { Object value = newMemberValues.get(memberName); if (value != null) { MemberValuePair newValuePair = createMemberValuePair(ast, memberName, value); // TODO: should attempt to preserve order listRewrite.insertLast(newValuePair, null); } else { // nothing to do } } for (String memberName : removedMembers) { MemberValuePair memberValuePair = ASTTools.memberValuePair(normalAnnotation, memberName); listRewrite.remove(memberValuePair, null); } // TODO: earlier implementation; to remove // for(String memberName: commonMembers) { // Object value = newMemberValues.get(memberName); // MemberValuePair memberValuePair = // ASTTools.memberValuePair(normalAnnotation, memberName); // if (value != null) { // MemberValuePair newValuePair = createMemberValuePair(ast, memberName, value); // if (memberValuePair == null) { // // TODO: should attempt to preserve the order here. // listRewrite.insertLast(newValuePair, null); // } else { // listRewrite.replace(memberValuePair, newValuePair, null); // } // } else { // if (memberValuePair == null) { // // nothing to do // } else { // listRewrite.remove(memberValuePair, null); // } // } // } }
From source file:edu.illinois.compositerefactorings.refactorings.NewClassCreator.java
License:Open Source License
public List<ResourceChange> createTopLevelParameterObject() throws CoreException { List<ResourceChange> changes = new ArrayList<ResourceChange>(); ICompilationUnit unit = getPackageFragment() .getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX); Assert.isTrue(!unit.exists());/*from w ww . j a v a 2s. co m*/ IJavaProject javaProject = unit.getJavaProject(); ICompilationUnit workingCopy = unit.getWorkingCopy(null); try { // create stub with comments and dummy type String lineDelimiter = StubUtility.getLineDelimiterUsed(javaProject); String fileComment = getFileComment(workingCopy, lineDelimiter); String typeComment = getTypeComment(workingCopy, lineDelimiter); String content = CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment, "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$ workingCopy.getBuffer().setContents(content); CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite(workingCopy); ASTRewrite rewriter = cuRewrite.getASTRewrite(); CompilationUnit root = cuRewrite.getRoot(); AST ast = cuRewrite.getAST(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); if (fSuperclassType != null) { importRewrite.addImport(fSuperclassType.resolveBinding()); } // retrieve&replace dummy type with real class ListRewrite types = rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY); ASTNode dummyType = (ASTNode) types.getOriginalList().get(0); TypeDeclaration classDeclaration = createClassDeclaration(getClassName(), cuRewrite); classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); Javadoc javadoc = (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY); rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null); types.replace(dummyType, classDeclaration, null); // Apply rewrites and discard workingcopy // Using CompilationUnitRewrite.createChange() leads to strange // results String charset = ResourceUtil.getFile(unit).getCharset(false); Document document = new Document(content); try { rewriter.rewriteAST().apply(document); TextEdit rewriteImports = importRewrite.rewriteImports(null); rewriteImports.apply(document); } catch (BadLocationException e) { throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error, e)); } String docContent = document.get(); CreateCompilationUnitChange compilationUnitChange = new CreateCompilationUnitChange(unit, docContent, charset); changes.add(compilationUnitChange); } finally { workingCopy.discardWorkingCopy(); } return changes; }
From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.ChangePublicToProtectedResolution.java
License:Open Source License
@Override protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException { Assert.isNotNull(rewrite);//from w ww. j a va2s . c om Assert.isNotNull(workingUnit); Assert.isNotNull(bug); TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass()); MethodDeclaration method = getMethodDeclaration(type, bug.getPrimaryMethod()); Modifier originalModifier = getPublicModifier(method); ListRewrite listRewrite = rewrite.getListRewrite(method, MethodDeclaration.MODIFIERS2_PROPERTY); Modifier protectedModifier = workingUnit.getAST().newModifier(PROTECTED_KEYWORD); listRewrite.replace(originalModifier, protectedModifier, null); }
From source file:edu.umd.cs.findbugs.quickfix.resolution.ChangePublicToProtectedResolution.java
License:Open Source License
@Override protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException { assert rewrite != null; assert workingUnit != null; assert bug != null; TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass()); MethodDeclaration method = getMethodDeclaration(type, bug.getPrimaryMethod()); Modifier originalModifier = getPublicModifier(method); ListRewrite listRewrite = rewrite.getListRewrite(method, MethodDeclaration.MODIFIERS2_PROPERTY); Modifier protectedModifier = workingUnit.getAST().newModifier(PROTECTED_KEYWORD); listRewrite.replace(originalModifier, protectedModifier, null); }
From source file:net.atos.optimus.m2t.merger.java.core.DefaultMergingStrategy.java
License:Open Source License
/** * Annotation attributes handlings for annotation's type located in the * generated annotation property file.// w ww.j ava2s . c o m * * @param annotationInTheExistingFragment * @param existingAnnotation * @param lw * @param generatedAnnotations * @param annoName */ private void mergeAnnotationAttributes(Annotation annotationInTheExistingFragment, Annotation annotationInTheGeneratedFragment, ListRewrite lw) { if (annotationInTheExistingFragment.isMarkerAnnotation()) { /* * The annotation used inside the existing fragment is a marker * annotation (annotation without attribute) */ if (!annotationInTheGeneratedFragment.isMarkerAnnotation()) { /* * The annotation used inside the generated fragment contains * one or many attributes. The annotation used inside the * generated fragment must be used in the result */ lw.replace(annotationInTheExistingFragment, annotationInTheGeneratedFragment, null); } } else { if (annotationInTheExistingFragment.isSingleMemberAnnotation()) { /* * The annotation used inside the existing fragment is a single * member annotation (annotation without only one attribute) */ if (annotationInTheGeneratedFragment.isSingleMemberAnnotation()) { /* * The annotation used inside the generated fragment * contains one value. Existing value must be replaced by * generated value. */ this.astr.replace(annotationInTheExistingFragment, annotationInTheGeneratedFragment, null); } else { if (annotationInTheGeneratedFragment.isNormalAnnotation()) { /* * The annotation used inside the generated fragment * contains several attributes. Existing value must be * replaced by generated value. */ lw.replace(annotationInTheExistingFragment, annotationInTheGeneratedFragment, null); } } } else { /* * The annotation used inside the existing fragment is a normal * annotation (annotation with several attributes) */ if (annotationInTheGeneratedFragment.isSingleMemberAnnotation()) { /* * What should be done in that case ? The existing * annotation has been probably enhance => Let the existing * content as before. */ } else { if (annotationInTheGeneratedFragment.isNormalAnnotation()) { /* * The annotation used inside the generated fragment * contains several attributes. Existing and generated * annotations must be merged. */ this.mergeAnnotationAttribute((NormalAnnotation) annotationInTheExistingFragment, (NormalAnnotation) annotationInTheGeneratedFragment); } } } } }
From source file:net.atos.optimus.m2t.merger.java.core.DefaultMergingStrategy.java
License:Open Source License
/** * Merge two annotations attribute/* w w w . j ava 2 s . c o m*/ */ @SuppressWarnings("unchecked") private void mergeAnnotationAttribute(NormalAnnotation annotationInTheExistingFragment, NormalAnnotation annotationInTheGeneratedFragment) { List<String> existingAnnotationAttributesToRemoved = new ArrayList<String>(1); List<MemberValuePair> existingAnnotationAttributes = annotationInTheExistingFragment.values(); List<MemberValuePair> generatedAnnotationAttributes = annotationInTheGeneratedFragment.values(); List<String> existingAnnotationAttributesNames = new ArrayList<String>(1); Map<String, MemberValuePair> generatedAnnotationAttributesMap = new HashMap<String, MemberValuePair>(1); for (MemberValuePair mvp : existingAnnotationAttributes) { existingAnnotationAttributesNames.add(mvp.getName().getFullyQualifiedName()); } for (MemberValuePair mvp : generatedAnnotationAttributes) { generatedAnnotationAttributesMap.put(mvp.getName().getFullyQualifiedName(), mvp); } for (MemberValuePair mvp : existingAnnotationAttributes) { if (generatedAnnotationAttributesMap.containsKey(mvp.getName().getFullyQualifiedName())) { /* * The attribute is present in the existing fragment AND The * attribute is present in the generated fragment => The * attribute present in the existing fragment must be removed * and the attribute present in the generated fragment must be * copied in the result */ ListRewrite lw = this.astr.getListRewrite(annotationInTheExistingFragment, NormalAnnotation.VALUES_PROPERTY); lw.replace(mvp, generatedAnnotationAttributesMap.get(mvp.getName().getFullyQualifiedName()), null); existingAnnotationAttributesToRemoved.add(mvp.getName().getFullyQualifiedName()); } } for (MemberValuePair mvp : generatedAnnotationAttributes) { if (!existingAnnotationAttributesNames.contains(mvp.getName().getFullyQualifiedName()) && !existingAnnotationAttributesToRemoved.contains(mvp.getName().getFullyQualifiedName())) { /* * The attribute is not present in the existing fragment AND The * attribute is present in the generated fragment => The * attribute present in the generated fragment must be copied in * the result */ ListRewrite lw = this.astr.getListRewrite(annotationInTheExistingFragment, NormalAnnotation.VALUES_PROPERTY); lw.insertFirst(mvp, null); } else { // Nothing to do } } }
From source file:org.eclipse.objectteams.otdt.internal.ui.text.correction.AddMethodMappingSignaturesProposal.java
License:Open Source License
private void addSignatureToCallinBases(ICompilationUnit cu, ASTRewrite rewrite, ImportRewrite imports, CallinMappingDeclaration mapping, TextEditGroup editGroup, IMethodBinding roleMethod) throws CoreException { @SuppressWarnings("unchecked") List<MethodSpec> oldBaseSpecs = mapping.getBaseMappingElements(); ListRewrite baseMethodsRewrite = rewrite.getListRewrite(mapping, CallinMappingDeclaration.BASE_MAPPING_ELEMENTS_PROPERTY); IMethodMappingBinding mappingBinding = mapping.resolveBinding(); if (mappingBinding != null) { // create proposal from exact methods IMethodBinding[] baseMethods = mappingBinding.getBaseMethods(); for (int i = 0; i < baseMethods.length; i++) { IMethodBinding baseMethod = baseMethods[i]; try { MethodSpec newSpec = OTStubUtility.createMethodSpec(cu, rewrite, imports, baseMethod, true); baseMethodsRewrite.replace(oldBaseSpecs.get(i), newSpec, editGroup); } catch (CoreException e) { OTDTUIPlugin.log(e);/*from w w w .j a v a2 s . c o m*/ } } } else { ITypeBinding[] roleParameters = roleMethod.getParameterTypes(); RoleTypeDeclaration role = (RoleTypeDeclaration) mapping.getParent(); for (int i = 0; i < oldBaseSpecs.size(); i++) { MethodSpec oldBaseSpec = oldBaseSpecs.get(i); // search matching base methods: List<IMethodBinding> matchingBaseMethods = new ArrayList<IMethodBinding>(); guessBaseMethod(role.resolveBinding(), oldBaseSpec.getName().getIdentifier(), roleParameters, true, matchingBaseMethods); if (matchingBaseMethods.size() == 0) throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.objectteams.otdt.jdt.ui", //$NON-NLS-1$ "Could not find a matching base method")); //$NON-NLS-1$ try { MethodSpec newSpec = OTStubUtility.createMethodSpec(cu, rewrite, imports, matchingBaseMethods.get(0), true); baseMethodsRewrite.replace(oldBaseSpecs.get(i), newSpec, editGroup); // do we have alternatives to propose? if (matchingBaseMethods.size() > 1) { addLinkedPosition(rewrite.track(newSpec), false, KEY_BASEMETHOD); for (IMethodBinding baseMethodBinding : matchingBaseMethods) { MethodSpec bSpec = OTStubUtility.createMethodSpec(cu, rewrite, imports, baseMethodBinding, true); addLinkedPositionProposal(KEY_BASEMETHOD, bSpec.toString(), null); } } } catch (CoreException e) { OTDTUIPlugin.log(e); } } } }
From source file:org.eclipse.objectteams.otdt.internal.ui.text.correction.MappingProposalSubProcessor.java
License:Open Source License
private static void makeReplacement(ASTRewrite rewrite, ASTNode oldNode, ASTNode newNode) { ASTNode parent = oldNode.getParent(); StructuralPropertyDescriptor desc = oldNode.getLocationInParent(); if (desc.isChildListProperty()) { ListRewrite listRewrite = rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) desc); listRewrite.replace(oldNode, newNode, null); } else {//from w w w .j ava 2s .c o m rewrite.set(parent, desc, newNode, null); } }
From source file:org.eclipse.pde.api.tools.ui.internal.markers.UpdateSinceTagOperation.java
License:Open Source License
public void run(IProgressMonitor monitor) { if (monitor != null && monitor.isCanceled()) { return;/*ww w . jav a 2s . c om*/ } if (monitor != null) { monitor.beginTask(MarkerMessages.UpdateSinceTagOperation_title, 3); } // retrieve the AST node compilation unit try { Integer charStartAttribute = (Integer) this.fMarker.getAttribute(IMarker.CHAR_START); int intValue = charStartAttribute.intValue(); IJavaElement javaElement = null; IJavaElement handleElement = null; if (intValue > 0) { IResource resource = this.fMarker.getResource(); javaElement = JavaCore.create(resource); } else { // this is a case where the marker is reported against the // MANIFEST.MF file String handle = (String) fMarker.getAttribute(IApiMarkerConstants.MARKER_ATTR_HANDLE_ID); if (handle != null) { handleElement = JavaCore.create(handle); } if (handleElement != null && handleElement.exists()) { javaElement = handleElement.getAncestor(IJavaElement.COMPILATION_UNIT); } } if (javaElement != null && javaElement.getElementType() == IJavaElement.COMPILATION_UNIT) { ICompilationUnit compilationUnit = (ICompilationUnit) javaElement; if (!compilationUnit.isWorkingCopy()) { // open an editor of the corresponding unit to "show" the // quickfix change JavaUI.openInEditor(compilationUnit); } ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(compilationUnit); if (intValue <= 0) { // try to use the name range of the corresponding element if (handleElement instanceof IMember) { IMember member = (IMember) handleElement; ISourceRange range = member.getNameRange(); if (range != null) { intValue = range.getOffset(); } else { range = member.getSourceRange(); if (range != null && range.getOffset() > 0) { intValue = range.getOffset(); } else { return; } } } else { return; } } parser.setFocalPosition(intValue); parser.setResolveBindings(true); Map<String, String> options = compilationUnit.getJavaProject().getOptions(true); options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); parser.setCompilerOptions(options); final CompilationUnit unit = (CompilationUnit) parser.createAST(new NullProgressMonitor()); BodyDeclaration node = null; NodeFinder nodeFinder = new NodeFinder(intValue); unit.accept(nodeFinder); if (monitor != null) { monitor.worked(1); } node = nodeFinder.getNode(); if (node != null) { unit.recordModifications(); AST ast = unit.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); if (IApiProblem.SINCE_TAG_MISSING == this.sinceTagType) { Javadoc docnode = node.getJavadoc(); if (docnode == null) { docnode = ast.newJavadoc(); // we do not want to create a new empty Javadoc node // in // the AST if there are no missing tags rewrite.set(node, node.getJavadocProperty(), docnode, null); } else { List<TagElement> tags = docnode.tags(); boolean found = false; loop: for (Iterator<TagElement> iterator = tags.iterator(); iterator.hasNext();) { TagElement element = iterator.next(); String tagName = element.getTagName(); if (TagElement.TAG_SINCE.equals(tagName)) { found = true; break loop; } } if (found) { return; } } ListRewrite lrewrite = rewrite.getListRewrite(docnode, Javadoc.TAGS_PROPERTY); // check the existing tags list TagElement newtag = ast.newTagElement(); newtag.setTagName(TagElement.TAG_SINCE); TextElement textElement = ast.newTextElement(); textElement.setText(this.sinceTagVersion); newtag.fragments().add(textElement); lrewrite.insertLast(newtag, null); } else { Javadoc docnode = node.getJavadoc(); List<TagElement> tags = docnode.tags(); TagElement sinceTag = null; for (Iterator<TagElement> iterator = tags.iterator(); iterator.hasNext();) { TagElement tagElement = iterator.next(); if (TagElement.TAG_SINCE.equals(tagElement.getTagName())) { sinceTag = tagElement; break; } } if (sinceTag != null) { List<TextElement> fragments = sinceTag.fragments(); if (fragments.size() >= 1) { TextElement textElement = fragments.get(0); StringBuffer buffer = new StringBuffer(); buffer.append(' ').append(this.sinceTagVersion); rewrite.set(textElement, TextElement.TEXT_PROPERTY, String.valueOf(buffer), null); } else { ListRewrite lrewrite = rewrite.getListRewrite(docnode, Javadoc.TAGS_PROPERTY); // check the existing tags list TagElement newtag = ast.newTagElement(); newtag.setTagName(TagElement.TAG_SINCE); TextElement textElement = ast.newTextElement(); textElement.setText(this.sinceTagVersion); newtag.fragments().add(textElement); lrewrite.replace(sinceTag, newtag, null); } } } try { if (monitor != null) { monitor.worked(1); } TextEdit edit = rewrite.rewriteAST(); compilationUnit.applyTextEdit(edit, monitor); if (monitor != null) { monitor.worked(1); } } finally { compilationUnit.reconcile(ICompilationUnit.NO_AST, false /* * don * 't * force * problem * detection */, null /* * use * primary * owner */, null /* * no * progress * monitor */); } } } } catch (CoreException e) { ApiUIPlugin.log(e); } finally { if (monitor != null) { monitor.done(); } } }