Example usage for org.eclipse.jdt.core IBuffer replace

List of usage examples for org.eclipse.jdt.core IBuffer replace

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IBuffer replace.

Prototype

public void replace(int position, int length, String text);

Source Link

Document

Replaces the given range of characters in this buffer with the given text.

Usage

From source file:org.jboss.tools.ws.jaxrs.ui.wizards.JaxrsElementCreationUtils.java

License:Open Source License

/**
 * Adds the given annotation with the given values on the given member, and
 * adds the given annotation name in the import declarations.
 * /*from  w  ww  .j av a  2 s.c  o  m*/
 * @param member
 * @param annotationFullyQualifiedName
 * @param annotationValues
 * @param imports
 * @throws JavaModelException
 */
public static void addAnnotation(final IMember member, final String annotationFullyQualifiedName,
        final List<String> annotationValues, final ImportsManager imports) throws JavaModelException {
    final ISourceRange sourceRange = member.getSourceRange();
    final ISourceRange javaDocRange = member.getJavadocRange();
    final IBuffer buf = member.getCompilationUnit().getBuffer();
    final String lineDelimiter = StubUtility.getLineDelimiterUsed(member.getJavaProject());
    final StringBuffer sb = new StringBuffer();
    final String annotationSimpleName = getSimpleName(annotationFullyQualifiedName);
    imports.addImport(annotationFullyQualifiedName);
    sb.append("@").append(annotationSimpleName);
    if (annotationValues != null && !annotationValues.isEmpty()) {
        sb.append('(');
        if (annotationValues.size() > 1) {
            sb.append('{');
        }
        for (Iterator<String> iterator = annotationValues.iterator(); iterator.hasNext();) {
            sb.append('"').append(iterator.next()).append('"');
            if (iterator.hasNext()) {
                sb.append(',');
            }
        }
        if (annotationValues.size() > 1) {
            sb.append('}');
        }
        sb.append(")");
    }
    sb.append(lineDelimiter);
    // insert the annotation ending with a line delimiter just before the
    // beginning of the code for the created type (but after the import
    // declarations)
    if (javaDocRange == null) {
        buf.replace(sourceRange.getOffset(), 0, sb.toString());
    } else {
        buf.replace(javaDocRange.getOffset() + javaDocRange.getLength() + lineDelimiter.length(), 0,
                sb.toString());
    }
    JavaModelUtil.reconcile(member.getCompilationUnit());
}

From source file:org.jboss.tools.ws.jaxrs.ui.wizards.JaxrsResourceCreationWizardPage.java

License:Open Source License

/**
 * Adds the comments on the given method, if the 'Add comments' option was
 * checked./*from  www.j a v  a 2s  .  c om*/
 * 
 * @param method
 *            the method on which comments should be added.
 */
private void addMethodComments(final IMethod method) {
    if (isAddComments()) {
        try {
            final String lineDelimiter = StubUtility.getLineDelimiterUsed(method.getJavaProject());
            final String comment = CodeGeneration.getMethodComment(method, null, lineDelimiter);
            if (comment != null) {
                final IBuffer buf = method.getCompilationUnit().getBuffer();
                buf.replace(method.getSourceRange().getOffset(), 0, comment);
            }
        } catch (CoreException e) {
            JavaPlugin.log(e);
        }
    }

}

From source file:org.seasar.s2junit4plugin.wizard.NewS2JUnit4TypeWizardPage.java

License:Apache License

/**
 * Creates the new type using the entered field values.
 * //ww  w  .ja va 2 s .  c om
 * @param monitor a progress monitor to report progress.
 * @throws CoreException Thrown when the creation failed.
 * @throws InterruptedException Thrown when the operation was canceled.
 */
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }

    monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8);

    IPackageFragmentRoot root = getPackageFragmentRoot();
    IPackageFragment pack = getPackageFragment();
    if (pack == null) {
        pack = root.getPackageFragment(""); //$NON-NLS-1$
    }

    if (!pack.exists()) {
        String packName = pack.getElementName();
        pack = root.createPackageFragment(packName, true, new SubProgressMonitor(monitor, 1));
    } else {
        monitor.worked(1);
    }

    boolean needsSave;
    ICompilationUnit connectedCU = null;

    try {
        String typeName = getTypeNameWithoutParameters();

        boolean isInnerClass = isEnclosingTypeSelected();

        IType createdType;
        ImportsManager imports;
        int indent = 0;

        Set /* String (import names) */ existingImports;

        String lineDelimiter = null;
        if (!isInnerClass) {
            lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());

            String cuName = getCompilationUnitName(typeName);
            ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, //$NON-NLS-1$
                    new SubProgressMonitor(monitor, 2));
            // create a working copy with a new owner

            needsSave = true;
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now a (primary) working copy
            connectedCU = parentCU;

            IBuffer buffer = parentCU.getBuffer();

            String simpleTypeStub = constructSimpleTypeStub();
            String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
            buffer.setContents(cuContent);

            CompilationUnit astRoot = createASTForImports(parentCU);
            existingImports = getExistingImports(astRoot);

            imports = new ImportsManager(astRoot);
            // add an import that will be removed again. Having this import solves 14661
            imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));

            String typeContent = null;
            if (isS2JUnit4()) {
                imports.addImport("org.junit.runner.RunWith");
                imports.addImport("org.seasar.framework.unit.Seasar2");
                typeContent = new StringBuffer("@RunWith(Seasar2.class)").append(lineDelimiter)
                        .append(constructTypeStub(parentCU, imports, lineDelimiter)).toString();

            } else {
                typeContent = constructTypeStub(parentCU, imports, lineDelimiter);
            }

            int index = cuContent.lastIndexOf(simpleTypeStub);
            if (index == -1) {
                AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
                int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
                int end = typeNode.getStartPosition() + typeNode.getLength();
                buffer.replace(start, end - start, typeContent);
            } else {
                buffer.replace(index, simpleTypeStub.length(), typeContent);
            }

            createdType = parentCU.getType(typeName);
        } else {
            IType enclosingType = getEnclosingType();

            ICompilationUnit parentCU = enclosingType.getCompilationUnit();

            needsSave = !parentCU.isWorkingCopy();
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now for sure (primary) a working copy
            connectedCU = parentCU;

            CompilationUnit astRoot = createASTForImports(parentCU);
            imports = new ImportsManager(astRoot);
            existingImports = getExistingImports(astRoot);

            // add imports that will be removed again. Having the imports solves 14661
            IType[] topLevelTypes = parentCU.getTypes();
            for (int i = 0; i < topLevelTypes.length; i++) {
                imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
            }

            lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType);
            StringBuffer content = new StringBuffer();

            String comment = getTypeComment(parentCU, lineDelimiter);
            if (comment != null) {
                content.append(comment);
                content.append(lineDelimiter);
            }

            content.append(constructTypeStub(parentCU, imports, lineDelimiter));
            IJavaElement sibling = null;
            if (enclosingType.isEnum()) {
                IField[] fields = enclosingType.getFields();
                if (fields.length > 0) {
                    for (int i = 0, max = fields.length; i < max; i++) {
                        if (!fields[i].isEnumConstant()) {
                            sibling = fields[i];
                            break;
                        }
                    }
                }
            } else {
                IJavaElement[] elems = enclosingType.getChildren();
                sibling = elems.length > 0 ? elems[0] : null;
            }

            createdType = enclosingType.createType(content.toString(), sibling, false,
                    new SubProgressMonitor(monitor, 2));

            indent = StubUtility.getIndentUsed(enclosingType) + 1;
        }
        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // add imports for superclass/interfaces, so types can be resolved correctly

        ICompilationUnit cu = createdType.getCompilationUnit();

        imports.create(false, new SubProgressMonitor(monitor, 1));

        JavaModelUtil.reconcile(cu);

        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // set up again
        CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);

        createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));

        // add imports
        imports.create(false, new SubProgressMonitor(monitor, 1));

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        ISourceRange range = createdType.getSourceRange();

        IBuffer buf = cu.getBuffer();
        String originalContent = buf.getText(range.getOffset(), range.getLength());
        Map options = pack.getJavaProject() != null ? pack.getJavaProject().getOptions(true) : null;
        String formattedContent = null;
        TextEdit edit = CodeFormatterUtil.format2(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, 0,
                originalContent.length(), indent, lineDelimiter, options);
        if (edit == null) {
            formattedContent = originalContent;
        } else {
            Document document = new Document(originalContent);
            try {
                edit.apply(document, TextEdit.NONE);
            } catch (BadLocationException e) {
                JavaPlugin.log(e); // bug in the formatter
                Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
            }
            formattedContent = document.get();
        }
        formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);
        if (!isInnerClass) {
            String fileComment = getFileComment(cu);
            if (fileComment != null && fileComment.length() > 0) {
                buf.replace(0, 0, fileComment + lineDelimiter);
            }
        }
        fCreatedType = createdType;

        if (needsSave) {
            cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
        } else {
            monitor.worked(1);
        }

    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
        monitor.done();
    }
}