Example usage for org.eclipse.jdt.core ITypeRoot getBuffer

List of usage examples for org.eclipse.jdt.core ITypeRoot getBuffer

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ITypeRoot getBuffer.

Prototype

public IBuffer getBuffer() throws JavaModelException;

Source Link

Document

Returns the buffer opened for this element, or null if this element does not have a buffer.

Usage

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  w  w  . ja v a  2  s . c  o m*/
 * <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   w w  w . j  a  v a  2 s .  c o m
 *   <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:cideplus.ui.astview.ASTView.java

License:Open Source License

private CompilationUnit internalSetInput(ITypeRoot input, int offset, int length, int astLevel)
        throws CoreException {
    if (input.getBuffer() == null) {
        throw new CoreException(getErrorStatus("Input has no buffer", null)); //$NON-NLS-1$
    }/*from  w w  w.j a va  2  s.  c  o m*/

    try {
        CompilationUnit root = createAST(input, astLevel, offset);
        resetView(root);
        if (root == null) {
            setContentDescription("AST could not be created."); //$NON-NLS-1$
            return null;
        }
        ASTNode node = NodeFinder.perform(root, offset, length);
        if (node != null) {
            fViewer.getTree().setRedraw(false);
            try {
                fASTLabelProvider.setSelectedRange(node.getStartPosition(), node.getLength());
                fViewer.setSelection(new StructuredSelection(node), true);
            } finally {
                fViewer.getTree().setRedraw(true);
            }
        }
        return root;

    } catch (RuntimeException e) {
        throw new CoreException(getErrorStatus("Could not create AST:\n" + e.getMessage(), e)); //$NON-NLS-1$
    }
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

public List<AutocompleteResponse.Completion> ProcessAutocompleteRequest(String contentFile, String typeRootId,
        int cursorPosition) throws Exception {
    if (ActiveTypeRoots.containsKey(typeRootId)) {
        ITypeRoot typeRoot = ActiveTypeRoots.get(typeRootId);
        typeRoot.getBuffer().setContents(contentFile.toCharArray());
        return Autocomplete(typeRoot, cursorPosition);
    }/*  www .  j a  v a  2  s  .com*/
    return null;
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

public List<ParamHelpResponse.Signature> ProcessParamHelpRequest(String contentFile, String typeRootId,
        int cursorPosition) throws Exception {
    if (ActiveTypeRoots.containsKey(typeRootId)) {
        ITypeRoot typeRoot = ActiveTypeRoots.get(typeRootId);
        typeRoot.getBuffer().setContents(contentFile.toCharArray());
        return ParamHelp(typeRoot, cursorPosition);
    }/* w w  w .  ja  v a 2  s .  c om*/
    return null;
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

public List<JavaElement> ProcessQuickInfoRequest(String fileParseContents, String typeRootId,
        int cursorPosition) throws Exception {
    if (ActiveTypeRoots.containsKey(typeRootId)) {
        ITypeRoot cu = ActiveTypeRoots.get(typeRootId);
        cu.getBuffer().setContents(fileParseContents.toCharArray());
        IJavaElement[] elements = cu.codeSelect(cursorPosition, 0);

        List<JavaElement> ret = new ArrayList<JavaElement>();

        long flags = JavaElementLabelComposer.ALL_FULLY_QUALIFIED | JavaElementLabelComposer.ALL_DEFAULT
                | JavaElementLabelComposer.M_PRE_RETURNTYPE | JavaElementLabelComposer.F_PRE_TYPE_SIGNATURE;
        for (IJavaElement element : elements) {
            StringBuffer buffer = new StringBuffer();
            JavaElementLabelComposer composer = new JavaElementLabelComposer(buffer);

            composer.appendElementLabel(element, flags);
            System.out.println(element.getPath().toString());

            JavaElement.Builder b = JavaElement.newBuilder().setDefinition(buffer.toString());

            String javaDoc = null;
            try {
                javaDoc = element.getAttachedJavadoc(null);
            } catch (JavaModelException jme) {
                jme.printStackTrace();//from   w  w  w  .  j  a v  a2s  . c  o m
            }
            if (javaDoc != null)
                b.setJavaDoc(javaDoc);
            ret.add(b.build());
        }
        return ret;
    }
    return null;
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

public List<FindDefinitionResponse.JavaElement> ProcessFindDefinintionRequest(String fileParseContents,
        String typeRootId, int cursorPosition) throws Exception {
    if (ActiveTypeRoots.containsKey(typeRootId)) {
        ITypeRoot cu = ActiveTypeRoots.get(typeRootId);
        cu.getBuffer().setContents(fileParseContents.toCharArray());
        IJavaElement[] elements = cu.codeSelect(cursorPosition, 0);

        List<FindDefinitionResponse.JavaElement> ret = new ArrayList<FindDefinitionResponse.JavaElement>();
        for (IJavaElement element : elements) {
            String definition = element.toString();
            String path = element.getResource() != null ? element.getResource().getLocation().toOSString()
                    : element.getPath().toOSString();
            //String path = element.getPath().makeAbsolute().toOSString(); // element.getPath().toString();

            boolean isAvailable = false;
            int posStart = -1;
            int posLength = 0;
            String contents = null;
            String classFileName = null;
            IClassFile classFileObj = null;

            ISourceReference srcRef = (ISourceReference) element;
            if (srcRef != null) {
                ISourceRange range = srcRef.getSourceRange();
                if (SourceRange.isAvailable(range)) {
                    isAvailable = true;/*www  . j a v a 2 s. c  o m*/
                    posStart = range.getOffset();
                    posLength = range.getLength();

                    //if (path.endsWith(".jar"))
                    //{
                    IOpenable op = element.getOpenable();
                    if (op != null && op instanceof IClassFile) {
                        IBuffer buff = op.getBuffer();
                        classFileObj = (IClassFile) op;
                        classFileName = classFileObj.getElementName();
                        contents = buff.getContents();
                    }
                    //}
                }
            }

            FindDefinitionResponse.JavaElement.Builder retItem = FindDefinitionResponse.JavaElement.newBuilder()
                    .setDefinition(definition).setFilePath(path).setHasSource(isAvailable)
                    .setPositionStart(posStart).setPositionLength(posLength);

            if (contents != null) {
                //int hashCode = classFileObj.hashCode();
                String handle = classFileObj.getHandleIdentifier();
                ActiveTypeRoots.put(handle, classFileObj);

                retItem.setFileName(classFileName);
                retItem.setTypeRootIdentifier(TypeRootIdentifier.newBuilder().setHandle(handle).build());
            }
            System.out.println(retItem.toString());
            if (contents != null) {
                retItem.setFileContents(contents);
            }
            ret.add(retItem.build());
        }
        return ret;
    }
    return null;
}

From source file:org.eclipse.ajdt.core.model.AJProjectModelFacade.java

License:Open Source License

/**
 * Open up the buffer to to convert from line number to offset
 * this is slow//w  w w  .  j a  v  a  2s  . c  om
 * We are always working in an AJCU with an aspect element
 * 
 * cache the results since it is likely that we will be 
 * calling this often for the same sloc
 */
private int offsetFromLine(ITypeRoot unit, ISourceLocation sloc) throws JavaModelException {
    if (sloc.getOffset() > 0) {
        return sloc.getOffset();
    }

    if (slocCache != null && slocCache.containsKey(sloc)) {
        return slocCache.get(sloc).intValue();
    }

    if (unit instanceof AJCompilationUnit) {
        AJCompilationUnit ajUnit = (AJCompilationUnit) unit;
        ajUnit.requestOriginalContentMode();
    }
    IBuffer buf = unit.getBuffer();
    if (unit instanceof AJCompilationUnit) {
        AJCompilationUnit ajUnit = (AJCompilationUnit) unit;
        ajUnit.discardOriginalContentMode();
    }
    if (buf != null) {
        int requestedLine = sloc.getLine();
        int currentLine = 1;
        int offset = 0;
        while (offset < buf.getLength() && currentLine < requestedLine) {
            if (buf.getChar(offset++) == '\n') {
                currentLine++;
            }
        }
        while (offset < buf.getLength() && Character.isWhitespace(buf.getChar(offset))) {
            offset++;
        }

        // cache
        if (slocCache == null) {
            slocCache = new HashMap<ISourceLocation, Integer>();
        }
        slocCache.put(sloc, new Integer(offset));
        return offset;
    }
    // no source code
    return 0;
}

From source file:org.eclipse.che.jdt.javadoc.ASTProvider.java

License:Open Source License

/**
 * Checks whether the given Java element has accessible source.
 *
 * @param je the Java element to test//from  www. ja  v a 2s .c om
 * @return <code>true</code> if the element has source
 * @since 3.2
 */
private static boolean hasSource(ITypeRoot je) {
    if (je == null || !je.exists())
        return false;

    try {
        return je.getBuffer() != null;
    } catch (JavaModelException ex) {
        LOG.error(ex.getMessage(), ex);
    }
    return false;
}

From source file:org.jboss.tools.vscode.java.internal.handlers.DocumentHighlightHandler.java

License:Open Source License

private List<DocumentHighlight> computeOccurrences(ITypeRoot unit, int line, int column) {
    if (unit != null) {
        try {/*from  w w w .  jav a2s . c om*/
            int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), line, column);
            OccurrencesFinder finder = new OccurrencesFinder();
            ASTParser parser = ASTParser.newParser(AST.JLS8);
            parser.setSource(unit);
            parser.setResolveBindings(true);
            ASTNode ast = parser.createAST(new NullProgressMonitor());
            if (ast instanceof CompilationUnit) {
                finder.initialize((CompilationUnit) ast, offset, 0);
                List<DocumentHighlight> result = new ArrayList<>();
                OccurrenceLocation[] occurrences = finder.getOccurrences();
                if (occurrences != null) {
                    for (OccurrenceLocation loc : occurrences) {
                        result.add(convertToHighlight(unit, loc));
                    }
                }
                return result;
            }
        } catch (JavaModelException e) {
            JavaLanguageServerPlugin
                    .logException("Problem with compute occurrences for" + unit.getElementName(), e);
        }
    }
    return Collections.emptyList();
}