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:at.bestsolution.fxide.jdt.editor.JDTJavaDocSupport.java

License:Open Source License

private static HtmlString getMemberJavaDoc(IMember member) throws JavaModelException {
    IBuffer buf = member.getOpenable().getBuffer();
    if (buf != null) {
        ISourceRange javadocRange = member.getJavadocRange();
        if (javadocRange != null) {
            String rawJavadoc = buf.getText(javadocRange.getOffset(), javadocRange.getLength());
            return JDTJavaDocSupport.toHtml(member, rawJavadoc);
        }/*from w w  w  .j a v  a 2  s  .c  om*/
    }
    return null;
}

From source file:at.bestsolution.fxide.jdt.text.javadoc.JavadocContentAccess2.java

License:Open Source License

private static String getHTMLContentFromSource(IJavaElement element) throws JavaModelException {
    IMember member;// w  w  w .  ja v  a 2  s . c o m
    if (element instanceof ILocalVariable) {
        member = ((ILocalVariable) element).getDeclaringMember();
    } else if (element instanceof ITypeParameter) {
        member = ((ITypeParameter) element).getDeclaringMember();
    } else if (element instanceof IMember) {
        member = (IMember) element;
    } else {
        return null;
    }

    IBuffer buf = member.getOpenable().getBuffer();
    if (buf == null) {
        return null; // no source attachment found
    }

    ISourceRange javadocRange = member.getJavadocRange();
    if (javadocRange == null) {
        if (canInheritJavadoc(member)) {
            // Try to use the inheritDoc algorithm.
            String inheritedJavadoc = javadoc2HTML(member, element, "/***/"); //$NON-NLS-1$
            if (inheritedJavadoc != null && inheritedJavadoc.length() > 0) {
                return inheritedJavadoc;
            }
        }
        return getJavaFxPropertyDoc(member);
    }

    String rawJavadoc = buf.getText(javadocRange.getOffset(), javadocRange.getLength());
    return javadoc2HTML(member, element, rawJavadoc);
}

From source file:ca.uvic.chisel.diver.sequencediagrams.sc.java.model.NodeFinder.java

License:Open Source License

/**
 * A visitor that maps a selection to a given ASTNode. The result node is
 * determined as follows:// w  ww. j a  va  2  s. c  om
 * <ul>
 *   <li>first the visitor tries to find a node that is covered by <code>start</code> and
 *       <code>length</code> where either <code>start</code> and <code>length</code> exactly
 *       matches the node or where the text covered before and after the node only consists
 *       of white spaces or comments.</li>
 *     <li>if no such node exists than the node that encloses the range defined by
 *       start and end is returned.</li>
 *   <li>if the length is zero than also nodes are considered where the node's
 *       start or end position matches <code>start</code>.</li>
 *   <li>otherwise <code>null</code> is returned.</li>
 * </ul>
 * 
 * @param root the root node from which the search starts
 * @param start the start offset
 * @param length the length
 * @param source the source of the compilation unit
 * 
 * @return the result node
 * @throws JavaModelException if an error occurs in the Java model
 * 
 * @since      3.0
 */
public static ASTNode perform(ASTNode root, int start, int length, ITypeRoot source) throws JavaModelException {
    NodeFinder finder = new NodeFinder(start, length);
    root.accept(finder);
    ASTNode result = finder.getCoveredNode();
    if (result == null)
        return null;
    Selection selection = Selection.createFromStartLength(start, length);
    if (selection.covers(result)) {
        IBuffer buffer = source.getBuffer();
        if (buffer != null) {
            IScanner scanner = ToolFactory.createScanner(false, false, false, false);
            scanner.setSource(buffer.getText(start, length).toCharArray());
            try {
                int token = scanner.getNextToken();
                if (token != ITerminalSymbols.TokenNameEOF) {
                    int tStart = scanner.getCurrentTokenStartPosition();
                    if (tStart == result.getStartPosition() - start) {
                        scanner.resetTo(tStart + result.getLength(), length - 1);
                        token = scanner.getNextToken();
                        if (token == ITerminalSymbols.TokenNameEOF)
                            return result;
                    }
                }
            } catch (InvalidInputException e) {
            }
        }
    }
    return finder.getCoveringNode();
}

From source file:ca.uvic.chisel.javasketch.internal.ast.NodeFinder.java

License:Open Source License

/**
 * Maps a selection to a given ASTNode, where the selection is given by a start and a length.
 * The result node is determined as follows:
 * <ul>//from   ww w .j  a v  a  2s  .  com
 *   <li>first the visitor tries to find a node that is covered by <code>start</code> and
 *       <code>length</code> where either <code>start</code> and <code>length</code> exactly
 *       matches the node or where the text covered before and after the node only consists
 *       of white spaces or comments.</li>
 *   <li>if no such node exists then the node that encloses the range defined by
 *       <code>start</code> and <code>length</code> is returned.</li>
 *   <li>if the length is zero then also nodes are considered where the node's
 *       start or end position matches <code>start</code>.</li>
 *   <li>otherwise <code>null</code> is returned.</li>
 * </ul>
 *
 * @param root the root node from which the search starts
 * @param start the given start
 * @param length the given length
 * @param source the source of the compilation unit
 *
 * @return the result node
 * @throws JavaModelException if an error occurs in the Java model
 */
public static ASTNode perform(ASTNode root, int start, int length, ITypeRoot source) throws JavaModelException {
    NodeFinder finder = new NodeFinder(root, start, length);
    ASTNode result = finder.getCoveredNode();
    if (result == null)
        return null;
    int nodeStart = result.getStartPosition();
    if (start <= nodeStart && ((nodeStart + result.getLength()) <= (start + length))) {
        IBuffer buffer = source.getBuffer();
        if (buffer != null) {
            IScanner scanner = ToolFactory.createScanner(false, false, false, false);
            try {
                scanner.setSource(buffer.getText(start, length).toCharArray());
                int token = scanner.getNextToken();
                if (token != ITerminalSymbols.TokenNameEOF) {
                    int tStart = scanner.getCurrentTokenStartPosition();
                    if (tStart == result.getStartPosition() - start) {
                        scanner.resetTo(tStart + result.getLength(), length - 1);
                        token = scanner.getNextToken();
                        if (token == ITerminalSymbols.TokenNameEOF)
                            return result;
                    }
                }
            } catch (InvalidInputException e) {
                // ignore
            } catch (IndexOutOfBoundsException e) {
                // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001
                return null;
            }
        }
    }
    return finder.getCoveringNode();
}

From source file:com.android.ide.eclipse.adt.internal.build.ConvertSwitchQuickFixProcessor.java

License:Open Source License

@Override
public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] location)
        throws CoreException {
    if (location == null || location.length == 0) {
        return null;
    }/*from ww  w . j  av a 2s .  co m*/
    ASTNode coveringNode = context.getCoveringNode();
    if (coveringNode == null) {
        return null;
    }

    // Look up the fully qualified name of the non-constant expression, if any, and
    // make sure it's R-something.
    if (coveringNode.getNodeType() == ASTNode.SIMPLE_NAME) {
        coveringNode = coveringNode.getParent();
        if (coveringNode == null) {
            return null;
        }
    }
    if (coveringNode.getNodeType() != ASTNode.QUALIFIED_NAME) {
        return null;
    }
    QualifiedName name = (QualifiedName) coveringNode;
    if (!name.getFullyQualifiedName().startsWith("R.")) { //$NON-NLS-1$
        return null;
    }

    IProblemLocation error = location[0];
    int errorStart = error.getOffset();
    int errorLength = error.getLength();
    int caret = context.getSelectionOffset();

    // Even though the hasCorrections() method above will return false for everything
    // other than non-constant expression errors, it turns out this getCorrections()
    // method will ALSO be called on lines where there is no such error. In particular,
    // if you have an invalid cast expression like this:
    //     Button button = findViewById(R.id.textView);
    // then this method will be called, and the expression will pass all of the above
    // checks. However, we -don't- want to show a migrate code suggestion in that case!
    // Therefore, we'll need to check if we're *actually* on a line with the given
    // problem.
    //
    // Unfortunately, we don't get passed the problemId again, and there's no access
    // to it. So instead we'll need to look up the markers on the line, and see
    // if we actually have a constant expression warning. This is not pretty!!

    boolean foundError = false;
    ICompilationUnit compilationUnit = context.getCompilationUnit();
    IResource file = compilationUnit.getResource();
    if (file != null) {
        IDocumentProvider provider = new TextFileDocumentProvider();
        try {
            provider.connect(file);
            IDocument document = provider.getDocument(file);
            if (document != null) {
                List<IMarker> markers = AdtUtils.findMarkersOnLine(IMarker.PROBLEM, file, document, errorStart);
                for (IMarker marker : markers) {
                    String message = marker.getAttribute(IMarker.MESSAGE, "");
                    // There are no other attributes in the marker we can use to identify
                    // the exact error, so we'll need to resort to the actual message
                    // text even though that would not work if the messages had been
                    // localized... This can also break if the error messages change. Yuck.
                    if (message.contains("constant expressions")) { //$NON-NLS-1$
                        foundError = true;
                    }
                }
            }
        } catch (Exception e) {
            AdtPlugin.log(e, "Can't validate error message in %1$s", file.getName());
        } finally {
            provider.disconnect(file);
        }
    }
    if (!foundError) {
        // Not a constant-expression warning, so do nothing
        return null;
    }

    IBuffer buffer = compilationUnit.getBuffer();
    boolean sameLine = false;
    // See if the caret is on the same line as the error
    if (caret <= errorStart) {
        // Search backwards to beginning of line
        for (int i = errorStart; i >= 0; i--) {
            if (i <= caret) {
                sameLine = true;
                break;
            }
            char c = buffer.getChar(i);
            if (c == '\n') {
                break;
            }
        }
    } else {
        // Search forwards to the end of the line
        for (int i = errorStart + errorLength, n = buffer.getLength(); i < n; i++) {
            if (i >= caret) {
                sameLine = true;
                break;
            }
            char c = buffer.getChar(i);
            if (c == '\n') {
                break;
            }
        }
    }

    if (sameLine) {
        String expression = buffer.getText(errorStart, errorLength);
        return new IJavaCompletionProposal[] { new MigrateProposal(expression) };
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringProposal.java

License:Open Source License

@Override
public String getAdditionalProposalInfo() {
    try {//from   www . jav a2  s.  c  o m
        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) {
        AdtPlugin.log(e, null);
    }

    return "Initiates the Extract String refactoring operation";
}

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

private Object findMethodWithAttachedDocInHierarchy(final MethodBinding method) throws JavaModelException {
    ReferenceBinding type = method.declaringClass;
    final SelectionRequestor requestor1 = (SelectionRequestor) this.requestor;
    return new InheritDocVisitor() {
        public Object visit(ReferenceBinding currType) throws JavaModelException {
            MethodBinding overridden = findOverriddenMethodInType(currType, method);
            if (overridden == null)
                return InheritDocVisitor.CONTINUE;
            TypeBinding args[] = overridden.parameters;
            String names[] = new String[args.length];
            for (int i = 0; i < args.length; i++) {
                names[i] = Signature.createTypeSignature(args[i].sourceName(), false);
            }/*from w  w w  . j  a v a  2  s .  co  m*/
            IMember member = (IMember) requestor1.findMethodFromBinding(overridden, names,
                    overridden.declaringClass);
            if (member == null)
                return InheritDocVisitor.CONTINUE;
            if (member.getAttachedJavadoc(null) != null) {
                // for binary methods with attached javadoc and no source attached
                return overridden;
            }
            IOpenable openable = member.getOpenable();
            if (openable == null)
                return InheritDocVisitor.CONTINUE;
            IBuffer buf = openable.getBuffer();
            if (buf == null) {
                // no source attachment found. This method maybe the one. Stop.
                return InheritDocVisitor.STOP_BRANCH;
            }

            ISourceRange javadocRange = member.getJavadocRange();
            if (javadocRange == null)
                return InheritDocVisitor.CONTINUE; // this method doesn't have javadoc, continue to look.
            String rawJavadoc = buf.getText(javadocRange.getOffset(), javadocRange.getLength());
            if (rawJavadoc != null) {
                return overridden;
            }
            return InheritDocVisitor.CONTINUE;
        }
    }.visitInheritDoc(type);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.LocalVariable.java

License:Open Source License

/**
 * @see org.eclipse.jdt.core.ISourceReference
 *//*from w  w  w. j av a 2s . c om*/
public String getSource() throws JavaModelException {
    IOpenable openable = this.parent.getOpenableParent();
    IBuffer buffer = openable.getBuffer();
    if (buffer == null) {
        return null;
    }
    ISourceRange range = getSourceRange();
    int offset = range.getOffset();
    int length = range.getLength();
    if (offset == -1 || length == 0) {
        return null;
    }
    try {
        return buffer.getText(offset, length);
    } catch (RuntimeException e) {
        return null;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.Member.java

License:Open Source License

public ISourceRange getJavadocRange() throws JavaModelException {
    ISourceRange range = getSourceRange();
    if (range == null)
        return null;
    IBuffer buf = null;
    if (isBinary()) {
        buf = getClassFile().getBuffer();
    } else {/*from  w w w  . ja va  2 s .  c  o  m*/
        ICompilationUnit compilationUnit = 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);
        try {
            scanner.setSource(buf.getText(start, length).toCharArray());
            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);
            }
        } catch (InvalidInputException ex) {
            // try if there is inherited Javadoc
        } catch (IndexOutOfBoundsException e) {
            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001
        }
    }
    return null;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.SourceRefElement.java

License:Open Source License

/**
 * @see ISourceReference/*from w ww.j ava 2  s .  c  om*/
 */
public String getSource() throws JavaModelException {
    IOpenable openable = getOpenableParent();
    IBuffer buffer = openable.getBuffer();
    if (buffer == null) {
        return null;
    }
    ISourceRange range = getSourceRange();
    int offset = range.getOffset();
    int length = range.getLength();
    if (offset == -1 || length == 0) {
        return null;
    }
    try {
        return buffer.getText(offset, length);
    } catch (RuntimeException e) {
        return null;
    }
}