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

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

Introduction

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

Prototype

public char getChar(int position);

Source Link

Document

Returns the character at the given position in this buffer.

Usage

From source file:org.eclipse.andmore.internal.refactorings.extractstring.ExtractStringProposal.java

License:Open Source License

@Override
public String getAdditionalProposalInfo() {
    try {//from  w ww  .  j ava  2 s  .c  om
        ASTNode coveringNode = mContext.getCoveringNode();
        int start = coveringNode.getStartPosition();
        int length = coveringNode.getLength();
        IBuffer buffer = mContext.getCompilationUnit().getBuffer();
        StringBuilder sb = new StringBuilder();
        String string = buffer.getText(start, length);
        string = ExtractStringRefactoring.unquoteAttrValue(string);
        String token = ExtractStringInputPage.guessId(string);

        // Look up the beginning and the end of the line (outside of the extracted string)
        // such that we can show a preview of the diff, e.g. if you have
        // foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
        // so we need to extract "foo.setTitle(" and ");".

        // Look backwards to the beginning of the line (and strip whitespace)
        int i = start - 1;
        while (i > 0) {
            char c = buffer.getChar(i);
            if (c == '\r' || (c == '\n')) {
                break;
            }
            i--;
        }
        String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();

        // Look forwards to the end of the line (and strip whitespace)
        i = start + length;
        while (i < buffer.getLength()) {
            char c = buffer.getChar(i);
            if (c == '\r' || (c == '\n')) {
                break;
            }
            i++;
        }
        String lineSuffix = buffer.getText(start + length, i - (start + length));

        // Should we show the replacement as just R.string.foo or
        // context.getString(R.string.foo) ?
        boolean useContext = false;
        ASTNode parent = coveringNode.getParent();
        if (parent != null) {
            int type = parent.getNodeType();
            if (type == ASTNode.ASSIGNMENT || type == ASTNode.VARIABLE_DECLARATION_STATEMENT
                    || type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
                    || type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
                useContext = true;
            }
        }

        // Display .java change:
        sb.append("...<br>"); //$NON-NLS-1$
        sb.append(linePrefix);
        sb.append("<b>"); //$NON-NLS-1$
        if (useContext) {
            sb.append("context.getString("); //$NON-NLS-1$
        }
        sb.append("R.string."); //$NON-NLS-1$
        sb.append(token);
        if (useContext) {
            sb.append(")"); //$NON-NLS-1$
        }
        sb.append("</b>"); //$NON-NLS-1$
        sb.append(lineSuffix);
        sb.append("<br>...<br>"); //$NON-NLS-1$

        // Display strings.xml change:
        sb.append("<br>"); //$NON-NLS-1$
        sb.append("&lt;resources&gt;<br>"); //$NON-NLS-1$
        sb.append("    <b>&lt;string name=\""); //$NON-NLS-1$
        sb.append(token);
        sb.append("\"&gt;"); //$NON-NLS-1$
        sb.append(string);
        sb.append("&lt;/string&gt;</b><br>"); //$NON-NLS-1$
        sb.append("&lt;/resources&gt;"); //$NON-NLS-1$

        return sb.toString();
    } catch (JavaModelException e) {
        AndmoreAndroidPlugin.log(e, null);
    }

    return "Initiates the Extract String refactoring operation";
}

From source file:org.eclipse.objectteams.otdt.internal.core.MethodMapping.java

License:Open Source License

public ISourceRange getJavadocRange() throws JavaModelException {
    ISourceRange range = this.getSourceRange();
    if (range == null)
        return null;
    IBuffer buf = null;
    if (this.isBinary()) {
        buf = this.getClassFile().getBuffer();
    } else {/*from  w  w  w .  j  a  v a  2  s .  c o  m*/
        ICompilationUnit compilationUnit = this.getCompilationUnit();
        if (!compilationUnit.isConsistent()) {
            return null;
        }
        buf = compilationUnit.getBuffer();
    }
    final int start = range.getOffset();
    final int length = range.getLength();
    if (length > 0 && buf.getChar(start) == '/') {
        IScanner scanner = ToolFactory.createScanner(true, false, false, false);
        scanner.setSource(buf.getText(start, length).toCharArray());
        try {
            int docOffset = -1;
            int docEnd = -1;

            int terminal = scanner.getNextToken();
            loop: while (true) {
                switch (terminal) {
                case ITerminalSymbols.TokenNameCOMMENT_JAVADOC:
                    docOffset = scanner.getCurrentTokenStartPosition();
                    docEnd = scanner.getCurrentTokenEndPosition() + 1;
                    terminal = scanner.getNextToken();
                    break;
                case ITerminalSymbols.TokenNameCOMMENT_LINE:
                case ITerminalSymbols.TokenNameCOMMENT_BLOCK:
                    terminal = scanner.getNextToken();
                    continue loop;
                default:
                    break loop;
                }
            }
            if (docOffset != -1) {
                return new SourceRange(docOffset + start, docEnd - docOffset + 1);
            }
        } catch (InvalidInputException ex) {
            // try if there is inherited Javadoc
        }
    }
    return null;
}

From source file:org.eclipse.wb.internal.core.utils.jdt.core.JavadocContentAccess.java

License:Open Source License

/**
 * @return the {@link Reader} for an {@link IMember}'s Javadoc comment content from the source
 *         attachment./*from  w w w.j  av  a 2  s  . c o m*/
 */
public static Reader getContentReader(IMember member, boolean allowInherited) throws Exception {
    // check current type
    {
        IBuffer buffer = member.isBinary() ? member.getClassFile().getBuffer()
                : member.getCompilationUnit().getBuffer();
        // no source attachment found
        if (buffer == null) {
            return null;
        }
        //
        ISourceRange range = member.getSourceRange();
        int start = range.getOffset();
        int length = range.getLength();
        if (length > 0 && buffer.getChar(start) == '/') {
            // prepare scanner
            IScanner scanner;
            {
                scanner = ToolFactory.createScanner(true, false, false, false);
                scanner.setSource(buffer.getCharacters());
                scanner.resetTo(start, start + length - 1);
            }
            // find last JavaDoc comment
            {
                int docOffset = -1;
                int docEnd = -1;
                {
                    int terminal = scanner.getNextToken();
                    while (org.eclipse.jdt.internal.corext.dom.TokenScanner.isComment(terminal)) {
                        if (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC) {
                            docOffset = scanner.getCurrentTokenStartPosition();
                            docEnd = scanner.getCurrentTokenEndPosition() + 1;
                        }
                        terminal = scanner.getNextToken();
                    }
                }
                // if comment found, return it
                if (docOffset != -1) {
                    return new JavaDocCommentReader(buffer, docOffset, docEnd);
                }
            }
        }
    }
    // check inherited
    if (allowInherited && member.getElementType() == IJavaElement.METHOD) {
        IMethod method = (IMethod) member;
        IMethod superMethod = CodeUtils.findSuperMethod(method);
        if (superMethod != null) {
            return getContentReader(superMethod, allowInherited);
        }
    }
    // not found
    return null;
}

From source file:org.jboss.tools.common.java.generation.JavaPropertyGenerator.java

License:Open Source License

public static String getLineDelimiterUsed(ICompilationUnit cu) {
    if (cu == null || !cu.exists()) {
        return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
    }/*  w  ww  .  ja  v a  2  s .  co m*/
    IBuffer buf = null;
    try {
        buf = cu.getBuffer();
    } catch (JavaModelException e) {
        ModelPlugin.getPluginLog().logError(e);
    }
    if (buf == null) {
        return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    int length = buf.getLength();
    for (int i = 0; i < length; i++) {
        char ch = buf.getChar(i);
        if (ch == SWT.CR) {
            if (i + 1 < length) {
                if (buf.getChar(i + 1) == SWT.LF) {
                    return "\r\n"; //$NON-NLS-1$
                }
            }
            return "\r"; //$NON-NLS-1$
        } else if (ch == SWT.LF) {
            return "\n"; //$NON-NLS-1$
        }
    }
    return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}

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

License:Open Source License

public static void addAnnotation(String qualifiedName, ICompilationUnit compilationUnit, IJavaElement element,
        String params, MultiTextEdit rootEdit) throws JavaModelException {
    IJavaElement workingCopyElement = findWorkingCopy(compilationUnit, element);
    if (workingCopyElement == null) {
        return;//from w w w  . j av a2s.c  om
    }

    if (!(workingCopyElement instanceof IMember))
        return;

    IMember workingCopyMember = (IMember) workingCopyElement;

    IAnnotation annotation = findAnnotation(workingCopyMember, qualifiedName);
    if (annotation != null && annotation.exists())
        return;

    CompilationUnit cuNode = ASTTools.buildASTRoot(compilationUnit);

    ASTNode elementNode = null;
    if (workingCopyElement instanceof JavaElement) {
        elementNode = ((JavaElement) workingCopyElement).findNode(cuNode);
    }

    boolean duplicateShortName = addImport(qualifiedName, compilationUnit, rootEdit);

    IBuffer buffer = compilationUnit.getBuffer();
    String shortName = getShortName(qualifiedName);

    if (duplicateShortName)
        shortName = qualifiedName;

    String str = AT + shortName + params;

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

    if (elementNode != null) {
        position = elementNode.getStartPosition();
        if (elementNode instanceof BodyDeclaration && ((BodyDeclaration) elementNode).getJavadoc() != null) {
            position += ((BodyDeclaration) elementNode).getJavadoc().getLength();
            char c = buffer.getChar(position);
            while ((c == C_CARRIAGE_RETURN || c == C_NEW_LINE) && position < buffer.getLength() - 2) {
                position++;
                c = buffer.getChar(position);
            }
        }
        while (position < buffer.getLength() - 1) {
            char c = buffer.getChar(position);
            if (c != C_CARRIAGE_RETURN && c != C_NEW_LINE && c != C_SPACE && c != C_TAB) {
                break;
            }
            position++;
        }
    }

    if (!(workingCopyMember instanceof ILocalVariable)) {

        str += compilationUnit.findRecommendedLineSeparator();

        str += getLeadingSpacesToInsert(position, buffer);

    } else {
        str += SPACE;
    }

    if (rootEdit != null) {
        TextEdit edit = new InsertEdit(position, str);
        rootEdit.addChild(edit);
    } else {
        buffer.replace(position, 0, str);

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

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

License:Open Source License

private static int getNumberOfSpacesToDelete(int startPosition, IBuffer buffer) {
    int position = startPosition;
    int numberOfSpaces = 0;
    if (position < buffer.getLength() - 1) {
        char c = buffer.getChar(position);
        while ((c == C_SPACE || c == C_TAB || c == C_NEW_LINE || c == C_CARRIAGE_RETURN)
                && position < buffer.getLength() - 1) {
            numberOfSpaces++;//from www  .  ja v  a 2 s  . c om
            position++;
            c = buffer.getChar(position);
        }
    }
    return numberOfSpaces;
}

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.  j a v  a2  s  .c  om
    }
    position++;
    if (position != startPosition) {
        return buffer.getText(position, startPosition - position);
    }
    return "";
}

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  ww  . j a v a 2 s  .  co  m*/
                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;
}