Example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite set

List of usage examples for org.eclipse.jdt.core.dom.rewrite ASTRewrite set

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite set.

Prototype

public final void set(ASTNode node, StructuralPropertyDescriptor property, Object value,
        TextEditGroup editGroup) 

Source Link

Document

Sets the given property of the given node.

Usage

From source file:com.android.ide.eclipse.adt.internal.lint.AddSuppressAnnotation.java

License:Open Source License

@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addSuppressAnnotation(IDocument document, ICompilationUnit compilationUnit,
        BodyDeclaration declaration) throws CoreException {
    List modifiers = declaration.modifiers();
    SingleMemberAnnotation existing = null;
    for (Object o : modifiers) {
        if (o instanceof SingleMemberAnnotation) {
            SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
            String type = annotation.getTypeName().getFullyQualifiedName();
            if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) {
                existing = annotation;// ww  w  .  ja  v  a2  s . co m
                break;
            }
        }
    }

    ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
    String local = importRewrite.addImport(FQCN_SUPPRESS_LINT);
    AST ast = declaration.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    if (existing == null) {
        SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
        newAnnotation.setTypeName(ast.newSimpleName(local));
        StringLiteral value = ast.newStringLiteral();
        value.setLiteralValue(mId);
        newAnnotation.setValue(value);
        ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
        listRewrite.insertFirst(newAnnotation, null);
    } else {
        Expression existingValue = existing.getValue();
        if (existingValue instanceof StringLiteral) {
            StringLiteral stringLiteral = (StringLiteral) existingValue;
            if (mId.equals(stringLiteral.getLiteralValue())) {
                // Already contains the id
                return null;
            }
            // Create a new array initializer holding the old string plus the new id
            ArrayInitializer array = ast.newArrayInitializer();
            StringLiteral old = ast.newStringLiteral();
            old.setLiteralValue(stringLiteral.getLiteralValue());
            array.expressions().add(old);
            StringLiteral value = ast.newStringLiteral();
            value.setLiteralValue(mId);
            array.expressions().add(value);
            rewriter.set(existing, VALUE_PROPERTY, array, null);
        } else if (existingValue instanceof ArrayInitializer) {
            // Existing array: just append the new string
            ArrayInitializer array = (ArrayInitializer) existingValue;
            List expressions = array.expressions();
            if (expressions != null) {
                for (Object o : expressions) {
                    if (o instanceof StringLiteral) {
                        if (mId.equals(((StringLiteral) o).getLiteralValue())) {
                            // Already contains the id
                            return null;
                        }
                    }
                }
            }
            StringLiteral value = ast.newStringLiteral();
            value.setLiteralValue(mId);
            ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY);
            listRewrite.insertLast(value, null);
        } else {
            assert false : existingValue;
            return null;
        }
    }

    TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
    TextEdit annotationEdits = rewriter.rewriteAST(document, null);

    // Apply to the document
    MultiTextEdit edit = new MultiTextEdit();
    // Create the edit to change the imports, only if
    // anything changed
    if (importEdits.hasChildren()) {
        edit.addChild(importEdits);
    }
    edit.addChild(annotationEdits);

    return edit;
}

From source file:com.android.ide.eclipse.adt.internal.lint.AddSuppressAnnotation.java

License:Open Source License

@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addTargetApiAnnotation(IDocument document, ICompilationUnit compilationUnit,
        BodyDeclaration declaration) throws CoreException {
    List modifiers = declaration.modifiers();
    SingleMemberAnnotation existing = null;
    for (Object o : modifiers) {
        if (o instanceof SingleMemberAnnotation) {
            SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
            String type = annotation.getTypeName().getFullyQualifiedName();
            if (type.equals(FQCN_TARGET_API) || type.endsWith(TARGET_API)) {
                existing = annotation;//from w w w .j ava  2 s  . co m
                break;
            }
        }
    }

    ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
    importRewrite.addImport("android.os.Build"); //$NON-NLS-1$
    String local = importRewrite.addImport(FQCN_TARGET_API);
    AST ast = declaration.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    if (existing == null) {
        SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
        newAnnotation.setTypeName(ast.newSimpleName(local));
        Expression value = createLiteral(ast);
        newAnnotation.setValue(value);
        ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
        listRewrite.insertFirst(newAnnotation, null);
    } else {
        Expression value = createLiteral(ast);
        rewriter.set(existing, VALUE_PROPERTY, value, null);
    }

    TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
    TextEdit annotationEdits = rewriter.rewriteAST(document, null);
    MultiTextEdit edit = new MultiTextEdit();
    if (importEdits.hasChildren()) {
        edit.addChild(importEdits);
    }
    edit.addChild(annotationEdits);

    return edit;
}

From source file:com.android.ide.eclipse.auidt.internal.lint.AddSuppressAnnotation.java

License:Open Source License

@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addSuppressAnnotation(IDocument document, ICompilationUnit compilationUnit,
        BodyDeclaration declaration) throws CoreException {
    List modifiers = declaration.modifiers();
    SingleMemberAnnotation existing = null;
    for (Object o : modifiers) {
        if (o instanceof SingleMemberAnnotation) {
            SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
            String type = annotation.getTypeName().getFullyQualifiedName();
            if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) {
                existing = annotation;/*w w  w .  j ava 2 s .c  o m*/
                break;
            }
        }
    }

    ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
    String local = importRewrite.addImport(FQCN_SUPPRESS_LINT);
    AST ast = declaration.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    if (existing == null) {
        SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
        newAnnotation.setTypeName(ast.newSimpleName(local));
        StringLiteral value = ast.newStringLiteral();
        value.setLiteralValue(mId);
        newAnnotation.setValue(value);
        ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
        listRewrite.insertFirst(newAnnotation, null);
    } else {
        Expression existingValue = existing.getValue();
        if (existingValue instanceof StringLiteral) {
            // Create a new array initializer holding the old string plus the new id
            ArrayInitializer array = ast.newArrayInitializer();
            StringLiteral old = ast.newStringLiteral();
            StringLiteral stringLiteral = (StringLiteral) existingValue;
            old.setLiteralValue(stringLiteral.getLiteralValue());
            array.expressions().add(old);
            StringLiteral value = ast.newStringLiteral();
            value.setLiteralValue(mId);
            array.expressions().add(value);
            rewriter.set(existing, VALUE_PROPERTY, array, null);
        } else if (existingValue instanceof ArrayInitializer) {
            // Existing array: just append the new string
            ArrayInitializer array = (ArrayInitializer) existingValue;
            StringLiteral value = ast.newStringLiteral();
            value.setLiteralValue(mId);
            ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY);
            listRewrite.insertLast(value, null);
        } else {
            assert false : existingValue;
            return null;
        }
    }

    TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
    TextEdit annotationEdits = rewriter.rewriteAST(document, null);

    // Apply to the document
    MultiTextEdit edit = new MultiTextEdit();
    // Create the edit to change the imports, only if
    // anything changed
    if (importEdits.hasChildren()) {
        edit.addChild(importEdits);
    }
    edit.addChild(annotationEdits);

    return edit;
}

From source file:com.android.ide.eclipse.auidt.internal.lint.AddSuppressAnnotation.java

License:Open Source License

@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types
private MultiTextEdit addTargetApiAnnotation(IDocument document, ICompilationUnit compilationUnit,
        BodyDeclaration declaration) throws CoreException {
    List modifiers = declaration.modifiers();
    SingleMemberAnnotation existing = null;
    for (Object o : modifiers) {
        if (o instanceof SingleMemberAnnotation) {
            SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
            String type = annotation.getTypeName().getFullyQualifiedName();
            if (type.equals(FQCN_TARGET_API) || type.endsWith(TARGET_API)) {
                existing = annotation;//from   w  w  w  .  j a  v  a2s . c  o  m
                break;
            }
        }
    }

    ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
    String local = importRewrite.addImport(FQCN_TARGET_API);
    AST ast = declaration.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);
    if (existing == null) {
        SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
        newAnnotation.setTypeName(ast.newSimpleName(local));
        NumberLiteral value = ast.newNumberLiteral(Integer.toString(mTargetApi));
        //value.setLiteralValue(mId);
        newAnnotation.setValue(value);
        ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty());
        listRewrite.insertFirst(newAnnotation, null);
    } else {
        Expression existingValue = existing.getValue();
        if (existingValue instanceof NumberLiteral) {
            // Change the value to the new value
            NumberLiteral value = ast.newNumberLiteral(Integer.toString(mTargetApi));
            rewriter.set(existing, VALUE_PROPERTY, value, null);
        } else {
            assert false : existingValue;
            return null;
        }
    }

    TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
    TextEdit annotationEdits = rewriter.rewriteAST(document, null);
    MultiTextEdit edit = new MultiTextEdit();
    if (importEdits.hasChildren()) {
        edit.addChild(importEdits);
    }
    edit.addChild(annotationEdits);

    return edit;
}

From source file:com.google.currysrc.api.process.JavadocUtils.java

License:Apache License

public static void addJavadocTag(ASTRewrite rewrite, BodyDeclaration node, String tagText) {
    Javadoc javadoc = node.getJavadoc();
    if (javadoc == null) {
        AST ast = node.getAST();/*w  ww .j a v a  2  s . co m*/
        javadoc = (Javadoc) ast.createInstance(Javadoc.class);
        rewrite.set(node, node.getJavadocProperty(), javadoc, null /* editGroup */);
    }
    addJavadocTag(rewrite, javadoc, tagText);
}

From source file:de.akra.idocit.java.services.JavadocGeneratorTest.java

License:Apache License

/**
 * This is not a real unit test. It is a trial to use the ITextFileBufferManager to
 * save the changes in a CompilationUnit.<br />
 * Test for//from   www  . j av a2s.  com
 * {@link JavaInterfaceGenerator#updateJavadocInAST(de.akra.idocit.java.structure.JavaInterfaceArtifact)}
 * .
 * 
 * @throws FileNotFoundException
 * @throws IOException
 * @throws BadLocationException
 * @throws MalformedTreeException
 * @throws CoreException
 * @throws ParsingException
 */
@Ignore
public void testJavaInterfaceGenerator2() throws FileNotFoundException, IOException, MalformedTreeException,
        BadLocationException, CoreException, ParsingException {

    ParserOutput output = JavaTestUtils
            .createCompilationUnit(AllIDocItJavaTests.SOURCE_DIR + "ParsingService2.java");
    CompilationUnit unit = output.getCompilationUnit();
    String originalCU = unit.toString();

    TypeDeclaration typeDecl = (TypeDeclaration) unit.types().get(0);
    AST ast = typeDecl.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);

    List<JavadocTagElement> jDocTags = new ArrayList<JavadocTagElement>();
    JavadocTagElement tagElem = new JavadocTagElement(TagElement.TAG_PARAM, "paramName",
            createParamDocumentations(), SignatureElement.EMPTY_SIGNATURE_ELEMENT);
    jDocTags.add(tagElem);

    List<TagElement> additionalTags = Collections.emptyList();
    Javadoc javadoc = JavaInterfaceGenerator.createOrUpdateJavadoc(jDocTags, additionalTags, ast.newJavadoc(),
            ast, null, JavadocGenerator.INSTANCE, null);

    rewriter.set(typeDecl, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null);

    // get the buffer manager
    ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
    IPath path = unit.getJavaElement().getPath();

    try {
        bufferManager.connect(path, LocationKind.IFILE, null);
        // retrieve the buffer
        ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);

        if (textFileBuffer != null) {
            logger.log(Level.INFO, "isSynchronized=" + textFileBuffer.isSynchronized());

            IDocument document = textFileBuffer.getDocument();

            logger.log(Level.INFO, document.toString());

            // ... edit the document ...
            TextEdit edit = rewriter.rewriteAST(document, null);
            edit.apply(document);

            // commit changes to underlying file
            textFileBuffer.commit(null /* ProgressMonitor */, false /* Overwrite */);
        } else {
            logger.log(Level.SEVERE, "textFileBuffer == null");
        }
    } finally {
        bufferManager.disconnect(path, LocationKind.IFILE, null);
    }

    String changedCU = unit.toString();

    logger.log(Level.INFO, originalCU);
    logger.log(Level.INFO, changedCU);
}

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());/* ww  w.  j a  va2s.  c o 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.illinois.compositerefactorings.steps.CreateNewSuperclass.java

License:Open Source License

@Override
public Collection<ASTRewriteCorrectionProposal> getProposals(Object input) throws CoreException {
    TypeDeclaration typeDeclaration = (TypeDeclaration) input;
    ASTNode node = typeDeclaration.getParent();
    AST ast = node.getAST();/*  w w  w.j  av  a2  s  .  c  o  m*/
    ASTRewrite rewrite = ASTRewrite.create(ast);
    String label = MessageFormat.format(CompositeRefactoringsMessages.CreateNewSuperclass_description,
            typeDeclaration.getName(), getCompilationUnit().getElementName());
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, getCompilationUnit(),
            rewrite, 0, image);
    TypeDeclaration newSuperclass = ast.newTypeDeclaration();
    newSuperclass.setName(ast.newSimpleName("Super" + typeDeclaration.getName()));
    ListRewrite listRewrite = rewrite.getListRewrite(node, CompilationUnit.TYPES_PROPERTY);
    listRewrite.insertLast(newSuperclass, null);
    rewrite.set(newSuperclass, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY,
            typeDeclaration.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY), null);
    rewrite.set(typeDeclaration, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, newSuperclass.getName(), null);
    Collection<ASTRewriteCorrectionProposal> proposals = new ArrayList<ASTRewriteCorrectionProposal>();
    proposals.add(proposal);
    return proposals;
}

From source file:edu.illinois.keshmesh.transformer.core.LCK02JFixer.java

License:Open Source License

@Override
public Change createChange(IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException {
    ITextFileBufferManager textFileBufferManager = null;
    try {//from  w ww  .  java  2 s. c  o m
        //Retrieving the Document out of IPath
        textFileBufferManager = FileBuffers.getTextFileBufferManager();
        textFileBufferManager.connect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor);
        ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(bugPosition.getSourcePath(),
                LocationKind.IFILE);
        IDocument document = textFileBuffer.getDocument();
        try {
            Logger.log(document.get(bugPosition.getFirstOffset(), bugPosition.getLength()));
        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }
        // Parsing the Document
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setSource(document.get().toCharArray());
        parser.setResolveBindings(true);
        CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(progressMonitor);

        //Rewriting the AST
        int bugLineOffset = document.getLineInformation(bugPosition.getFirstLine() - 1).getOffset();
        int bugLineLength = document.getLineInformation(bugPosition.getFirstLine() - 1).getLength();
        String bugLineContent = document.get(bugLineOffset, bugLineLength);
        String syncCommand = "synchronized";

        int syncIndex = bugLineContent.indexOf(syncCommand);
        int start_comment_index = bugLineContent.indexOf("/*");
        int end_comment_index = bugLineContent.indexOf("*/");
        String temp_bugLineContent = bugLineContent;
        int temp_syncIndex = syncIndex;
        int temp_beginIndex = 0;

        // there is a possibility of having synchronized word within comments
        while (start_comment_index >= 0 && end_comment_index > 0 && temp_bugLineContent.length() > 0
                && temp_syncIndex > start_comment_index) {
            temp_beginIndex += (end_comment_index + 2);
            temp_bugLineContent = temp_bugLineContent.substring(end_comment_index + 2);
            temp_syncIndex = temp_bugLineContent.indexOf(syncCommand);
            start_comment_index = temp_bugLineContent.indexOf("/*");
            end_comment_index = temp_bugLineContent.indexOf("*/");
            syncIndex = temp_beginIndex + temp_syncIndex;
        }

        String bugLineContentAfterSynch = bugLineContent.substring(syncIndex + syncCommand.length());
        int openParenthesisIndex = bugLineContentAfterSynch.indexOf('(') + syncIndex + syncCommand.length();
        int myFirstOffset = bugLineOffset + syncIndex;
        int index = openParenthesisIndex;
        int pcounter = 1;
        while (pcounter != 0 && index < bugLineLength) {
            index++;
            if (bugLineContent.charAt(index) == ')') {
                pcounter--;
            } else if (bugLineContent.charAt(index) == '(') {
                pcounter++;
            }
        }

        int myLastOffset = bugLineOffset + index;
        ASTNode monitorNode = NodeFinder.perform(compilationUnit, myFirstOffset,
                myLastOffset - myFirstOffset + 1);
        SynchronizedStatement synchronizedStatement = (SynchronizedStatement) monitorNode;
        AST ast = synchronizedStatement.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);

        ASTParser expressionParser = ASTParser.newParser(AST.JLS3);
        expressionParser.setKind(ASTParser.K_EXPRESSION);
        expressionParser
                .setSource(CollectionUtils.getTheOnlyElementOf(fixInformation.getTypeNames()).toCharArray());
        ASTNode astNode = expressionParser.createAST(progressMonitor);
        rewriter.set(synchronizedStatement, SynchronizedStatement.EXPRESSION_PROPERTY, astNode, null);
        TextEdit textEdit = rewriter.rewriteAST(document, null);
        try {
            textEdit.apply(document);
        } catch (MalformedTreeException e) {
            e.printStackTrace();
        } catch (BadLocationException e) {
            e.printStackTrace();
        }

        //Committing changes to the source file
        textFileBuffer.commit(progressMonitor, true);
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    } finally {
        textFileBufferManager.disconnect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor);
    }
    return null;
}

From source file:net.atos.optimus.m2t.merger.java.core.JavaCodeMerger.java

License:Open Source License

/**
 * Merge javadoc comment from existingFragment and generatedFragment to an
 * AST Rewrite object instance. This method is call only when
 * {@code existingFragment} is marked as generated and
 * {@code generatedFragment} exist.//from  ww w .  j a va2s. com
 * 
 * @param existingFragment
 *            The existing fragment
 * @param generatedFragment
 *            The generated fragment
 * @param astr
 *            The ASTRewrite object instance containing the merge result
 */
protected void mergeJavadoc(BodyDeclaration existingFragment, BodyDeclaration generatedFragment,
        ASTRewrite astr) {
    boolean existingCommentIsGenerated = false;
    boolean generatedCommentIsGenerated = false;
    boolean existingCommentFound = true;
    boolean generatedCommentFound = true;

    try {
        existingCommentIsGenerated = isJavadocCommentGenerated(existingFragment.getJavadoc());
    } catch (IllegalArgumentException iae) {
        existingCommentFound = false;
    }

    try {
        generatedCommentIsGenerated = isJavadocCommentGenerated(generatedFragment.getJavadoc());
    } catch (IllegalArgumentException iae) {
        generatedCommentFound = false;
    }

    if (existingCommentIsGenerated) {
        if (!generatedCommentFound) {
            if (MergerLogger.enabled())
                MergerLogger.log(MergerLoggerMessages.MERGER_REMOVE_JAVADOC.value(
                        JavaCodeHelper.getName(existingFragment),
                        JavaCodeHelper.getDescription(existingFragment)));

            astr.remove(existingFragment.getJavadoc(), null);
        } else if (generatedCommentIsGenerated) {
            if (MergerLogger.enabled())
                MergerLogger.log(MergerLoggerMessages.MERGER_REPLACE_JAVADOC.value(
                        JavaCodeHelper.getName(existingFragment), JavaCodeHelper.getName(generatedFragment)));

            astr.replace(existingFragment.getJavadoc(), generatedFragment.getJavadoc(), null);
        }
    } else if (!existingCommentFound && generatedCommentIsGenerated) {
        if (MergerLogger.enabled())
            MergerLogger.log(
                    MergerLoggerMessages.MERGER_ADD_JAVADOC.value(JavaCodeHelper.getName(existingFragment)));
        astr.set(existingFragment, existingFragment.getJavadocProperty(), generatedFragment.getJavadoc(), null);
    }
}