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

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

Introduction

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

Prototype

public String getText(int offset, int length) throws IndexOutOfBoundsException;

Source Link

Document

Returns the given range of text in this buffer.

Usage

From source file:org.jboss.tools.common.refactoring.MarkerResolutionUtils.java

License:Open Source License

private static String getLeadingSpacesToInsert(int startPosition, IBuffer buffer) {
    int position = startPosition;
    while (position >= 0) {
        char c = buffer.getChar(position);
        if (c == C_CARRIAGE_RETURN || c == C_NEW_LINE)
            break;
        position--;/*  w  w  w  .  ja  v  a 2 s  . c o m*/
    }
    position++;
    if (position != startPosition) {
        return buffer.getText(position, startPosition - position);
    }
    return "";
}

From source file:org.jboss.tools.common.refactoring.MarkerResolutionUtils.java

License:Open Source License

public static void deleteImportForAnnotation(String qualifiedName, IAnnotation annotation,
        ICompilationUnit compilationUnit, IBuffer buffer, MultiTextEdit rootEdit) throws JavaModelException {
    IImportDeclaration importDeclaration = compilationUnit.getImport(qualifiedName);
    IImportContainer importContainer = compilationUnit.getImportContainer();
    if (importDeclaration.exists() && importContainer.exists()) {
        int importSize = importContainer.getSourceRange().getOffset()
                + importContainer.getSourceRange().getLength();

        if (rootEdit != null) {
            int annotationStart = annotation.getSourceRange().getOffset();
            int annotationEnd = annotationStart + annotation.getSourceRange().getLength();
            String textBefore = buffer.getText(importSize, annotationStart - importSize);
            String textAfter = buffer.getText(annotationEnd, buffer.getLength() - annotationEnd);
            if (checkImport(textBefore, qualifiedName) && checkImport(textAfter, qualifiedName)) {
                int numberOfSpaces = 0;
                if (!isLastImport(importContainer, importDeclaration)) {
                    numberOfSpaces = getNumberOfSpacesToDelete(importDeclaration.getSourceRange().getOffset()
                            + importDeclaration.getSourceRange().getLength(), buffer);
                }/*from w  w  w .j a  va2 s .co  m*/

                TextEdit edit = new DeleteEdit(importDeclaration.getSourceRange().getOffset(),
                        importDeclaration.getSourceRange().getLength() + numberOfSpaces);
                rootEdit.addChild(edit);
            }
        } else {
            String text = buffer.getText(importSize, buffer.getLength() - importSize);
            if (checkImport(text, qualifiedName)) {
                importDeclaration.delete(false, new NullProgressMonitor());
            }
        }
    }

    if (rootEdit == null) {
        synchronized (compilationUnit) {
            compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, null);
        }
    }
}

From source file:org.jboss.tools.common.ui.marker.AddSuppressWarningsMarkerResolution.java

License:Open Source License

private CompilationUnitChange addAnnotation(String name, ICompilationUnit compilationUnit, IJavaElement element,
        ASTNode node) throws JavaModelException {
    if (!(element instanceof ISourceReference))
        return null;

    ISourceReference workingCopySourceReference = (ISourceReference) element;

    IBuffer buffer = compilationUnit.getBuffer();

    int position = workingCopySourceReference.getSourceRange().getOffset();

    if (node != null) {
        position = node.getStartPosition();
        if (node instanceof BodyDeclaration && ((BodyDeclaration) node).getJavadoc() != null) {
            position += ((BodyDeclaration) node).getJavadoc().getLength();
            char c = buffer.getChar(position);
            while ((c == '\r' || c == '\n') && position < buffer.getLength() - 2) {
                position++;/*from w w w .ja v a 2s  .  com*/
                c = buffer.getChar(position);
            }
        }
        while (position < buffer.getLength() - 1) {
            char c = buffer.getChar(position);
            if (c != '\r' && c != '\n' && c != ' ' && c != '\t') {
                break;
            }
            position++;
        }
    }

    String str = AT + name;

    if (!(workingCopySourceReference instanceof ILocalVariable)) {

        str += compilationUnit.findRecommendedLineSeparator();

        int index = position;
        while (index >= 0) {
            char c = buffer.getChar(index);
            if (c == '\r' || c == '\n')
                break;
            index--;
        }
        index++;
        if (index < position) {
            String spaces = buffer.getText(index, position - index);
            str += spaces;
        }

    } else {
        str += SPACE;
    }

    CompilationUnitChange change = new CompilationUnitChange("", compilationUnit);

    InsertEdit edit = new InsertEdit(position, str);

    change.setEdit(edit);

    return change;
}

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

License:Apache License

/**
 * Creates the new type using the entered field values.
 * //from  www. j  a  va2s.  c  o m
 * @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();
    }
}